当我var_dump($q)
时,我可以看到要插入到mysql数据库中的记录,但是当我尝试执行此操作$result = mysqli_query($con,$q);
时,系统没有返回错误消息,也不是记录插入。
<?php
$con = @mysqli_connect("localhost", "root", "", "troubleshoot_db") or
die(mysqli_error("Couldn't Establish a Connection"));
if( isset($_POST['submit']) )
{
$Grade = $_POST['Grade'];
foreach( $Grade as $key => $v )
{
$fault_code = $key;
$q = sprintf( 'INSERT INTO `history_tb` VALUES ("%s", "%s", "%s", "%s", "%s")', $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']);
//var_dump($q);
$result = mysqli_query($con,$q);
}
}
?>
答案 0 :(得分:1)
INSERT INTO表(a,b)VALUES(1,2),(2,3),(3,4);
答案 1 :(得分:0)
除了其他任何事情之外,有两件事需要解决。
将您的代码更改为以下内容(仅在if语句中修改):
<?php
$con = @mysqli_connect("localhost", "root", "", "troubleshoot_db") or
die(mysqli_error("Couldn't Establish a Connection"));
if( isset($_POST['submit']) )
{
$Grade = $_POST['Grade'];
$stmt = $mysqli->prepare("INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)"); //Prepare the sql command
foreach ($Grade as $key => $v )
{
// Assuming all are strings for now
$stmt->bind_param("sssss", $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']); // Bind the values in order to the ?'s
$stmt->execute(); // Execute the completed sql command
}
$stmt->close(); // Close the database connection
}
?>
我们在这里做的是说我的SQL是
INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)`
现在循环遍历您的数组,并使用循环的每个部分给出的参数调用此SQL。
这解决了在使用预准备语句时不使用预准备语句和循环的前两个问题。
试试这个,看看是否插入了记录
我还要检查foreach是否正确,可能需要
foreach ($Grade as $v)
但没有看到我无法确认的数据。
您还可以进一步添加错误处理:
if ($stmt = $mysqli->prepare("INSERT INTO `history_tb` VALUES (?, ?, ?, ?, ?)"))
{
foreach ($Grade as $key => $v )
{
// Assuming all are strings for now
// Bind the values in order to the ?'s or log error
if(!$stmt->bind_param("sssss", $v['troubleshoot_type'] , $v['troubleshoot_result'], $v['possible_solution'], $v['reg_id'], $v['date']))
{
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
// Execute the completed sql command or log error
if (!$stmt->execute())
{
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
}
$stmt->close(); // Close the database connection
}
else
{
die('prepare() failed: ' . htmlspecialchars($con->error));
}
编辑:添加错误处理
答案 2 :(得分:0)
$ query =&#34; INSERT INTO table_name
(name
,address
)VALUES(&#39; jony&#39;,&#39; test1&#39;) ,(&#39; bob&#39;,&#39; test2&#39;)&#34 ;;
的mysql_query($查询);