如上所述,我想在sql表中保存来自var_char(_ $ post)的数据,以及for loop中的下拉列表中的数据。我使用这个:
if (isset($_POST['submit']) && $_GET['action'] == 'schedule'){
$sdate = $_POST['start-date'];
$dateQ = "INSERT INTO schedule (schedule_id,user_email,date,morning,afternoon,evening) VALUES ('','$email','$sdate','$morningId','$afternoonId','$eveningId')";
if($dateQ) {
echo 'success';
}
else {
echo 'fail';
}
尽管它返回成功,但表仍然为空。即使我得到正确的话,我如何从for循环中插入表值?这样:
<?php
for ($i = 1; $i <= $correctDays; $i++) {
?>
<div>
<hr>
<h2>Schedule for day <?php echo $i; ?></h2>
<hr>
</div>
<div>
<h3>Pick an activity from 09:00-14:00:</h3>
</div>
<div style="text-align:center;">
<select name="morning<?php echo $i; ?>" style="text-align:center;">
<?php
while ($row = mysqli_fetch_assoc($morningR)) {
echo '<option value="' . $row['id'] . '">' . $row['sightname']. '</option>';
}
mysqli_data_seek($morningR, 0);
?>
</select>
</div>
<div>
<h3>Pick an activity from 14:00-18:00:</h3>
</div>
<div style="text-align:center;">
<select name="afternoon<?php echo $i; ?>" style="text-align:center;">
<?php
while ($row = mysqli_fetch_assoc($afternoonR)) {
echo '<option value="' . $row['id'] . '">' . $row['sightname'] . '</option>';
}
mysqli_data_seek($afternoonR, 0);
?>
</select>
</div>
<div>
<h3>Pick an activity from 18:00-24:00:</h3>
</div>
<div style="text-align:center;">
<select name="evening<?php echo $i; ?>" style="text-align:center;">
<?php
while ($row = mysqli_fetch_assoc($eveningR)) {
echo '<option value="' . $row['id'] . '">' . $row['sightname'] . '</option>';
}
mysqli_data_seek($eveningR, 0);
?>
</select>
</div>
<?php
}
?>
您必须运行查询,而不是将查询存储在变量中。
首先,您必须建立数据库连接:
/** REPLACE THE ARGUMENTS WITH PROPER VALUE BELOW **/
$con = new mysqli("YourHost", "Username", "Password", "DatabaseName");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %sn", mysqli_connect_error());
exit();
}
然后,您可以运行查询:
if (isset($_POST['submit']) && $_GET['action'] == 'schedule'){
$sdate = $_POST['start-date'];
$stmt = $con->prepare("INSERT INTO schedule (user_email, date, morning, afternoon, evening) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("ssiii", $email, $sdate, $morningId, $afternoonId, $eveningId);
$stmt->execute();
$stmt->close();
}
顺便说一句,您从哪里获得其他变量(例如,$ email,$ moverdid,$ sperthid,$ nightid)?希望您在插入查询之前宣布它们。
您可以在此处阅读有关准备好的语句的更多信息。