2014-10-20 38 views
0

我正在嘗試使用名爲$title的數組中的字符串填充SQL表。
這是我的PHP代碼:爲什麼我的PHP foreach循環只向SQL插入一個值?

// To store the values to insert into the database tables. 
$cid = 0; // Primary key. 
$dates = array(); 
$number = array(); 
$title = array("aaa", "bbb", "ccc"); 
$description = array(); 

// For connecting to database. 
$user = 'root'; 
$pass = ''; 
$db = 'contractsdb'; 

// Assign HTML file contents to $content. 
$content = file_get_contents('C:\xampp\htdocs\HTMLParser/tester.html'); 

// Load HTML page into Document Object Model for parsing HTML. 
$dom = new DOMDocument;  
$dom->loadHTML($content); 

// Connect to DB and check connection. 
$con=mysqli_connect("localhost", "$user", "$pass", "$db"); 
if (mysqli_connect_errno()) { 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
} 

// Insert the values into the database contracts table. 
foreach ($dom->getElementsByTagName('a') as $link) { 
    $sql = "INSERT INTO contracts (CID, TITLE) 
          VALUES ('$cid', '$title[$cid]')"; 
    echo "1 record added<BR>"; 
    $cid++; 
} 

// Error message if fail. 
if (!mysqli_query($con, $sql)) { 
    die('Error: ' . mysqli_error($con)); 
} 

// Close connection to database. 
mysqli_close($con); 

當我運行通過XAMPP這個代碼,看看錶,我得到這個:
enter image description here
正如你所看到的,只有一行添加 。我錯過了什麼?
語法錯誤foreach

HTML頁面打印出3個「1記錄添加」,爲什麼不包含3行?

回答

2

您在每個循環中覆蓋了$sql變量。

$sql = 'INSERT INTO contracts (CID, TITLE) VALUES '; 

foreach ($dom->getElementsByTagName('a') as $link) { 
    $sql .= "($cid, '$title[$cid]'),"; // $cid is INT, so don't use quotes, in the second case you should you real_escape_string. 
    $cid++; 
} 

if (!mysqli_query($con, rtrim($sql, ','))) {...} 
+0

好的,謝謝。我現在看到我的錯誤。 :) – 2014-10-20 10:59:03

2

一切都很好。

正如你所看到的,你在foreach循環中有回聲,但在外循環中有mysqli_query。所以你只執行一條語句:

INSERT INTO contracts (CID, TITLE) VALUES (2, 'ccc') 
相關問題