2014-12-05 80 views
0

我必须创建一个php脚本来读取url列表并将它们插入到mysql数据库中。 问题是它只插入第一行然后停止。阅读urls-csv并将它们插入到mysql中

<?php 
 
\t $conn=mysql_connect("my_servername","my_username","my_password") or die (mysql_error()); \t 
 
\t mysql_select_db("my_dbname") or die (mysql_error()); \t 
 

 
\t $url = array("url1.csv", 
 
\t \t \t \t "url2.csv", \t 
 
\t \t \t \t "url3.csv", \t 
 
\t \t \t \t . 
 
\t \t \t \t . \t 
 
\t \t \t \t . \t 
 
\t \t \t \t "url15.csv", \t 
 
\t \t \t \t); \t 
 

 
\t for ($i=0; $i<15; $i++) 
 
\t { \t 
 
\t \t $url_go = file_get_contents($url[$i]); 
 
\t \t \t 
 
\t \t $z = array_filter(explode("\x0A",$url_go[$i])); 
 
\t \t \t 
 
\t 
 
\t \t $counter=0; 
 
\t foreach($z as $k=>$v) 
 
\t { 
 
\t \t if($metr>2) 
 
\t \t { 
 
\t \t $y=((explode(';',rtrim($v,";")))); 
 
\t \t $sql = 'INSERT INTO `mysql_table_name` (name_of_column_1,name_of_column_2, name_of_column_3, name_of_column_4, name_of_column_5, name_of_column_6,name_of_column_7,name_of_column_8,name_of_column_9,name_of_column_10,name_of_column_11,name_of_column_12,name_of_column_13, name_of_column_14,name_of_column_15, name_of_column_16) 
 
\t \t \t VALUES ('.$y[0].', '.$y[1].', '.$y[2].', '.$y[3].', '.$y[4].', '.$y[5].', '.$y[6].', '.$y[7].', '.$y[8].', '.$y[9].', '.$y[10].', '.$y[11].', '.$y[12].', '.$y[13].', '.$y[14].' , '.$y[15].')'; 
 
\t \t } 
 
\t \t $counter++; 
 
\t } 
 
\t } 
 
\t $result=mysql_query($sql) or die('Query failed:' . mysql_error()); 
 
\t mysql_close($conn); 
 
?>

数据库已经与Navicat的创建。 这些网址是csv类型的。就像我的数据库中的列有相同的列表,但我不想插入csv-urls的前3行

+2

**警告**:由于这些参数不是[妥善转义](http://bobby-tables.com/php),所以这是非常不安全的。您应该**绝不**将用户数据直接放入查询中:它会创建一个巨大的[SQL注入漏洞](http://bobby-tables.com/)。 'mysql_query'是一个过时的接口,不应该被使用,它将被从PHP中删除。像[PDO这样的现代化替代品并不难学](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/)。像[PHP The Right Way](http://www.phptherightway.com/)这样的指南解释了最佳实践。 – tadman 2014-12-05 18:51:30

+0

'$ metr'是什么? – 2014-12-05 18:53:44

回答

0

首先,注意@有关过时的mysql()函数和需要正确转义数据以避免SQL注入的tadaman。

您在数据库中只获取一个条目的原因是因为您的mysql_query语句不在循环内部,所以只有最后的$ sql变量实际上被传递给mysql_query调用,该调用仅运行一次。

1

您的查询执行需要在您的第二个for循环中,因为$ sql变量不断被覆盖并且只执行一次。

$sql = 'INSERT INTO `mysql_table_name` (name_of_column_1,name_of_column_2, name_of_column_3, name_of_column_4, name_of_column_5, name_of_column_6,name_of_column_7,name_of_column_8,name_of_column_9,name_of_column_10,name_of_column_11,name_of_column_12,name_of_column_13, name_of_column_14,name_of_column_15, name_of_column_16) 
     VALUES ('.$y[0].', '.$y[1].', '.$y[2].', '.$y[3].', '.$y[4].', '.$y[5].', '.$y[6].', '.$y[7].', '.$y[8].', '.$y[9].', '.$y[10].', '.$y[11].', '.$y[12].', '.$y[13].', '.$y[14].' , '.$y[15].')'; 

mysql_query($sql) or die('Query failed:' . mysql_error()); 
+0

现在我得到这个查询失败:查询是空的 – piou 2014-12-05 19:33:35

相关问题