$name = $_POST["name"];
$address = $_POST["address"];
$city = $_POST["city"];
$state = $_POST["state"];
$zipcode = $_POST["zipcode"];
$country = $_POST["country"];
$month = $_POST["month"];
$day = $_POST["day"];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO birthdays (name, address, city, state, zipcode, country, month, day)
VALUES ($_POST["name"], $_POST["address"], $_POST["city"], $_POST["state"], $_POST["zipcode"], $_POST["country"], $_POST["month"], $_POST["day"])";
if ($conn->query($sql) === TRUE) {
echo "You have been added to the birthday list";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
数据库前缀是否需要包含在登录/数据库中?我现在很困惑。
sacrmfuw_sjay
带有前缀.. sjay
没有前缀
答案 0 :(得分:2)
如果我们要在SQL文本中包含文字值,则必须正确转义任何可能不安全的值。 mysqli_real_escape_string
函数是为我们自定义编写的。
要创建包含文字值的SQL文本,我们可以这样做:
$sql = "INSERT INTO birthdays (name, address, city, state, zipcode, country, month, day)"
. " VALUES"
. " ('" . $conn->real_escape_string( $_POST["name"] ) . "'"
. ", '" . $conn->real_escape_string( $_POST["address"] ) . "'"
. ", '" . $conn->real_escape_string( $_POST["city"] ) . "'"
. ", '" . $conn->real_escape_string( $_POST["state"] ) . "'"
. ", '" . $conn->real_escape_string( $_POST["zipcode"] ) . "'"
. ", '" . $conn->real_escape_string( $_POST["country"] ) . "'"
. ", '" . $conn->real_escape_string( $_POST["month"] ) . "'"
. ", '" . $conn->real_escape_string( $_POST["day"] ) . "'"
. ")";
mysqli_real_escape_string
函数用于包含在语句中的值。如果标识符(列名,表名)中的任何一个是MySQL保留字,则通常需要通过将标识符括在反引号字符中来正确转义。
首选模式,作为在SQL文本中包含文字值的替代方法,是将预处理语句与绑定占位符一起使用。像这样的静态SQL语句:
$sql = "INSERT INTO birthdays (name, address, city, state, zipcode, country, month, day)"
. " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
然后将SQL文本准备到语句中,并将 bind_param 值准备到语句中,然后执行语句。