为什么我的PHP foreach循环只向SQL插入一个值?

时间:2014-10-20 10:54:33

标签: php sql xampp

我正在尝试使用名为$title的数组中的字符串填充SQL表。
这是我的PHP代码:

// 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批&#34; 1条记录添加&#34;,为什么表格不包含3行?

2 个答案:

答案 0 :(得分: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, ','))) {...}

答案 1 :(得分:2)

一切都好。

正如你所看到的,你在foreach循环中有回声,但在循环中有mysqli_query。所以你只执行一个语句:

INSERT INTO contracts (CID, TITLE) VALUES (2, 'ccc')