我是PHP的新手。我想将已选中复选框的状态更新为0.我想将userid和boxid作为复选框插入另一个表中。但是,我的代码无法更新和插入。
这是我的代码:
if(isset($_POST['Next']))
{
foreach($_POST['boxs'] as $f => $value){
$sql = "UPDATE box SET status = '0' WHERE boxid = '$f'";
mysqli_query($con,$sql) or die(mysqli_error($con));
$result = "INSERT INTO booked(username, boxid) VALUES('$_POST[username]', '$f')";
mysqli_query($con,$result) or die(mysqli_error($con));
}
}
这是我的复选框:
<?php
$query = "SELECT * FROM box WHERE status = 1";
$result = @mysqli_query($con, $query);
$num_rows = @mysqli_num_rows($result);
$disable = '';
if (!$num_rows){
$disable = 'disabled="disabled"';
}
?>
<form method = "post" action = "">
<input type='checkbox' name="boxs[]" id="1.1" value ="1.1" <?php echo $disable ?>/>
<label for="1.1" class="background1"></label> <br/>
<input type='checkbox' name="boxs[]" id="1.2" value ="1.2"<?php echo $disable ?>/>
<label for="1.2" class="background2"></label>
<br/>
<input type='checkbox' name="boxs[]" id="1.3" value ="1.3"<?php echo $disable ?>/>
<label for="1.3" class="background2"></label>
<input type="submit" name="Next" id="Next" value="next" />
</form>
那么,知道我的代码有什么问题吗?
答案 0 :(得分:0)
像这样更改,您使用了错误的引号,加上$conn
函数缺少mysqli_query
参数
if(isset($_POST['Next']))
{
foreach($_POST['boxs'] as $f => $value){
$sql = "UPDATE box SET status = '0' WHERE boxid = '$f'";
mysqli_query($con,$sql) or die(mysqli_error($con));
$result = "INSERT INTO booked(username, boxid) VALUES('$_POST[username]', '$f')";
mysqli_query($con,$result) or die(mysqli_error($con));
}
}
答案 1 :(得分:0)
如果您在程序上致电mysqli_query,则需要首先连接到数据库:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
然后在您进行查询时传递连接:
mysqli_query($link,$sql) or die(mysqli_error($con));
最后,关闭连接:
mysqli_close($link);
答案 2 :(得分:0)
您可以使用以下方法来避免使用直接替换值,而不是使用直接替换值。
这有助于解决您的问题。
使用MySQLi(用于MySQL):
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}