I want to prepare an SQL insert statement inside PHP for loop, my statement is something like this
$insert_stmt = "";
for($x=1; $x<=$all_property[duration]; $x++) {
$insert_stmt .= "INSERT INTO `schedule` VALUES ($all_property[serial], $_POST[Day$x])";
echo $insert_stmt;
mysqli_free_result($insert_stmt); // Free result set for next query
}
wherein I expect the result to be like
INSERT INTO `schedule` VALUES ($all_property[serial], $_POST[Day1] //for first loop
INSERT INTO `schedule` VALUES ($all_property[serial], $_POST[Day2] //for second loop
And so on, but I am getting error
syntax error, unexpected '$x' (T_VARIABLE), expecting ']' in schedule.php on line 163
so, if any one can help me rectify what is wrong in my query.
Updated:
As the fields are not constant and also they are string, you need to quote them, so just use this line:
$insert_stmt = "INSERT INTO schedule VALUES (‘".$all_property[serial]."’, ‘".$_POST["Day".$x]."’)";
no, day1 and day2 are not constant values, these are the fields $_POST[] fileds generated from below table
for ($x = 1; $x <= $all_property['duration']; $x++) { $date_result = mysqli_query($connection, "SELECT DATE_ADD(dur_from,INTERVAL $x-1 DAY) AS dur_from FROM batch_details
WHERE serial=1"); $today_date = mysqli_fetch_assoc($date_result); echo' " size="12" value=""> " size="20" placeholder="Subject or Topic" maxlength="50" required> " size="18" placeholder="Room No" maxlength="3" pattern="[0-9]{3}" required> " size="18" placeholder="Main Lecturer ID" maxlength="3" pattern="[A-Za-z]{3}" required> " size="18" placeholder="Subs Lecturer ID" maxlength="3" pattern="[A-Za-z]{3}" required> " size="20" placeholder="Subject or Topic" maxlength="50" required> " size="18" placeholder="Room No" maxlength="3" pattern="[0-9]{3}" required> " size="18" placeholder="Main Lecturer ID" maxlength="3" pattern="[A-Za-z]{3}" required> " size="18" placeholder="Subs Lecturer ID" maxlength="3" pattern="[A-Za-z]{3}" required> " size="20" placeholder="Subject or Topic" maxlength="50" required> " size="18" placeholder="Room No" maxlength="3" pattern="[0-9]{3}" required> " size="18" placeholder="Main Lecturer ID" maxlength="3" pattern="[A-Za-z]{3}" required> " size="18" placeholder="Subs Lecturer ID" maxlength="3" pattern="[A-Za-z]{3}" required> ';
wherein, depending on the "duration" (which is basically no of days) the input field gets generated with name="Day$x" and then again I have to insert this value to another table.
Yes, the above line did solve the problem. And so the issue may be closed now.