php - 数据未插入数据库。不确定我做错了什么

标签 php mysql

<分区>

$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 没有前缀

最佳答案

如果我们要在 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 文本中包含文字值的替代方案,首选模式是使用准备好的语句绑定(bind)占位符。像这样的静态 SQL 语句:

  $sql = "INSERT INTO birthdays (name, address, city, state, zipcode, country, month, day)"
  . " VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

然后将SQL文本准备成一条语句,bind_param语句的值,然后执行这条语句。

http://php.net/manual/en/mysqli-stmt.bind-param.php

关于php - 数据未插入数据库。不确定我做错了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40663532/

相关文章:

php - 循环嵌套菜单

mysql - SQL - 如何为参数提供 "AS"值

mysql - 重叠日期的 SQL 触发器

php - 在 Codeigniter 应用程序中获取查询的行数

javascript - 使用 Next 按钮遍历数组

javascript - PHP中选择下拉项时如何打开第二个条件输入表单

php - $_GET 变量在分页代码中未定义

Php和Sql,非undefined时为undefined index

php - 不存在的表不会引发错误

php - 如何在codeigniter中减去时间和日期?