有点卡在这里(和新手) 我试图将数据从数组插入数据库,但不知道如何提取它: `
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Determine how many categories there are
$cnt = count($_POST['cat']);
$insertArr = array();
for ($i = 0; $i<$cnt; $i++){
$insertArr[] = "('" . ($_POST['cat'][$i]) . "', '" . ($_POST['grade'][$i]) . "')";
}
$q = "INSERT INTO grit (feed, grade) VALUES ('$insertArr[$i]', '$insertArr[$i]')";
$stmt = mysqli_prepare($dbc, $q);
// For debugging purposes:
if (!$stmt) echo mysqli_stmt_error($stmt);
//mysqli_stmt_bind_param($stmt, 'ss', $final_[0], $final_[1]);
// Execute the query:
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt) >= 1) { // If it ran OK.
// Print a message:
echo '<h4>feedback product has been added!</h4>';
// Clear $_POST:
$_POST = array();
} else { // If it did not run OK.
trigger_error('feedback could not be added due to a system error. We apologize for any inconvenience.');
}
}
`
数组似乎没问题,但没有任何内容传递给数据库。
答案 0 :(得分:1)
for ($i = 0; $i<$cnt; $i++){
$insertArr[] = "('" . ($_POST['cat'][$i]) . "', '" . ($_POST['grade'][$i]) . "')";
}
就像已经提到的那样,当你在查询中使用循环索引时,你已经在这里结束了for循环。
只需添加一件事:您应该逃避查询,否则,人们可能会将奇怪的东西写入您的数据库,并可能使用它来销毁您的数据。
例如,使用: mysql_real_escape_string
答案 1 :(得分:0)
您的查询应为:
$q = "INSERT INTO grit (feed, grade) VALUES ('" . $insertArr[$i]. "', '". $insertArr[$i] ."')";
另外它不在循环中,你正在使用循环索引......
试试:
$mysqli = new mysqli("localhost", "CHANGE", "CHANGE", "stackoverflow");
// This is my test array, remove that
$_POST = array ('cat' => array('meowy', 'kitty'), 'grade' => array(1,2));
$cnt = count($_POST['cat']);
for ($i = 0; $i<$cnt; $i++){
$q = "INSERT INTO grit (feed, grade) VALUES ('" . $_POST['cat'][$i] . "', '" . $_POST['grade'][$i] . "')";
$stmt = $mysqli->prepare($q);
// For debugging purposes:
if (!$stmt) echo mysqli_stmt_error($stmt);
// Execute the query:
$stmt->execute();
if (mysqli_stmt_affected_rows($stmt) >= 1) { // If it ran OK.
// Print a message:
echo '<h4>feedback product has been added!</h4>';
} else { // If it did not run OK.
trigger_error('feedback could not be added due to a system error. We apologize for any inconvenience.');
}
}
注意:请记住,您必须清理超级全局POST阵列中的数据。永远不要使用来自用户的数据而不确保数据是您实际期望的! 你应该改进你的代码。
答案 2 :(得分:0)
if(isset($_POST['timetab'])){
$cos=$_POST['course'];
$dat=$_POST['date'];
$tim=$_POST['time'];
$c=count($cos);
/*a for loop for each value per column . It also works as a multi-row insertion*/
for($i=0;$i<=$c;$i++)
{
$sql="INSERT INTO timetable (course_module, date, time) VALUES('$cos[$i]', '$dat[$i]', '$tim[$i]')";
$ins=mysqli_query($conlog, $sql);
}
echo(!mysqli_affected_rows($conlog))?"QUERY WRONG":"QUERY SUCCESS";
}