嗨,我的网站上有一个联系表格,用户可以在其中选择填写一些字段,然后单击提交按钮后将数据保存到数据库中,所有这些都工作正常,直到我决定从SQL注入中清理我的代码,正如我最初提到的,在尝试从SQL注入中清理它之前,它工作正常,如下面的代码所示
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
//insert to database
$insert =mysqli_query($connect,"INSERT INTO $db_table VALUES (to simplify code i do not write this part)");
}
?>
现在我必须填写所有下拉列表和复选框,否则它会给出错误"列''不能为空"。此外,我无法将日期和时间插入数据库,它给出了相同的错误。这是我在SQL注入中保护它时的代码: <form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
if(isset($_POST['submit'])){
//insert to database
$query = mysqli_prepare($connect, "INSERT INTO $db_table VALUES (?,?,?,?)");
/* bind parameters for markers */
mysqli_stmt_bind_param( $query, "ssss", $_POST[name],$_POST['check1'],$_POST['case'],$_POST['date_clicked']);
// execute query
if ( mysqli_stmt_execute($query) ) {
echo "Successfully inserted " . mysqli_affected_rows($connect) . " row";
} else {
echo "Error occurred: " . mysqli_error($connect);
}
}
?>
请帮助我
确保变量存在。这是必要的,因为例如,如果未选中,您的复选框将为 null,这可能是您正在使用的表的问题。您可以设置默认值,然后将其插入。
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$check1 = !empty($_POST['check1']) ? $_POST['check1'] : '';
$case = !empty($_POST['case']) ? $_POST['case'] : '';
$date_clicked = date('Y-m-d H:i:s');
// prepare and bind
$stmt = $connect->prepare("INSERT INTO `$db_table` (`name`, `check1`, `case`, `date_clicked`) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $name, $check1, $case, $date_clicked);
$stmt->execute();
$stmt->close();