2014-12-05 103 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

相關問題