我创建了一个包含quest_id和问题列的表并尝试使用PHP代码更新它们,但是我的代码中只有最后一个语句实际更新了表,我的意思是实际上最后一个更新命令有效,是有没有办法更新它们,或者有人可以帮我修复当前错误吗?
<?php
$servername = "localhost";
$con = mysqli_connect("localhost","dnm","dnm","login1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$q = array($_POST['q1'],$_POST['q2'], $_POST['q3'], $_POST['q4'], $_POST['q5'], $_POST['q6'], $_POST['q7'], $_POST['q8'], $_POST['q9'], $_POST['q10'], $_POST['q11'], $_POST['q12'], $_POST['q13'], $_POST['q14'], $_POST['q15'] );
if($q[0] == '' OR $q[1] == '' OR $q[2] =='' OR $q[3] =='' OR $q[4] == '' OR $q[5] == '' OR $q[6] == '' OR $q[7]== '' OR $q[8] == '' OR $q[9] == '' OR $q[10] == '' OR $q[11] == '' OR $q[12] == '' OR $q[13] == '' OR $q[14] == ''){
echo "<script>alert('Not all the questions are finished')</script>";
echo"<script>window.open('class.html','_self')</script>";
}
else {
$sql= "UPDATE login1.questions SET question = '$q[0]' WHERE questions.quest_id = 1";
$sql= "UPDATE login1.questions SET question = '$q[1]' WHERE questions.quest_id = 2";
$sql= "UPDATE login1.questions SET question = '$q[2]' WHERE questions.quest_id = 3";
$sql= "UPDATE login1.questions SET question = '$q[3]' WHERE questions.quest_id = 4";
$sql= "UPDATE login1.questions SET question = '$q[4]' WHERE questions.quest_id = 5";
$sql= "UPDATE login1.questions SET question = '$q[5]' WHERE questions.quest_id = 6";
$sql= "UPDATE login1.questions SET question = '$q[6]' WHERE questions.quest_id = 7";
$sql= "UPDATE login1.questions SET question = '$q[7]' WHERE questions.quest_id = 8";
$sql= "UPDATE login1.questions SET question = '$q[8]' WHERE questions.quest_id = 9";
$sql= "UPDATE login1.questions SET question = '$q[9]' WHERE questions.quest_id = 10";
$sql= "UPDATE login1.questions SET question = '$q[10]' WHERE questions.quest_id = 11";
$sql= "UPDATE login1.questions SET question = '$q[11]' WHERE questions.quest_id = 12";
$sql= "UPDATE login1.questions SET question = '$q[12]' WHERE questions.quest_id = 13";
$sql= "UPDATE login1.questions SET question = '$q[13]' WHERE questions.quest_id = 14";
$sql= "UPDATE login1.questions SET question = '$q[14]' WHERE questions.quest_id = 15";
echo "<script>alert('Success!')</script>";}
if (mysqli_query($con, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($con);
}
mysqli_close($con);
?>
答案 0 :(得分:5)
您只执行最后一次查询。
使用此代替大量代码,$sql
是。
for ($i = 1; $i <= 15; $i++) {
$sql= "UPDATE login1.questions SET question = '".$q[($i - 1)]."' WHERE questions.quest_id = " . $i;
mysqli_query($con, $sql);
}