我正在處理基於龐大數據的項目。我爲PHP中的每個數據創建了數組。現在我想將它插入到MySQL數據庫中。使用PHP將數組數據值插入MySQL數據庫表
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxxx";
$db_name = "xxxxxxx";
// Create connection
$link = mysql_connect($servername, $username, $password);
if(!$link){
echo "Failed" .mysql_connect_error();
}
mysql_select_db($db_name);
$data = array (
[1] => array(
'eng_title' => "john",
'content' => "john",
'category' => "john",
),
[2] => array(
'eng_title' => "john",
'content' => "john",
'category' => "john",
),
[3] => array(
'eng_title' => "john",
'content' => "john",
'category' => "john",
),
);
if(is_array($data)){
$sql = "INSERT INTO `table_a`(`eng_title`, `content`, `category`) values";
$valuesArr = array();
foreach($data as $row){
$eng_title = mysql_real_escape_string($row['eng_title']);
$content = mysql_real_escape_string($row['content']);
$category = mysql_real_escape_string($row['category']);
$valuesArr[] = "('$eng_title', '$content', '$category')";
}
$sql .= implode(',', $valuesArr);
echo $sql;
mysql_query($sql) or exit(mysql_error());
}
?>
這是我執行代碼時出現的消息。
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
我在其他程序中使用MySQLi,我想我正在使用最新版本的MySQL,這就是爲什麼上述程序無法正常工作。
從$ sql中刪除'(當你執行echo時,你能給我們看什麼樣的$ sql) –
在你的foreach中插入你的sql查詢。 – aldrin27