【问题标题】:SQL INSERT fails even if the new row is in the DB?即使新行在数据库中,SQL INSERT 也会失败?
【发布时间】:2014-07-30 06:05:42
【问题描述】:

我在 PHP 类中使用 mysqli。

我要执行这个查询:

INSERT INTO notifications (userid, content, uniq, link) VALUES (48, "[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9c602a02a26114a625", "http://website/somepost")

失败,显示错误:

You have an error in your query etc. to use near '"[2014-07-30] Nomid has edited the post \"Somepost\"", "934512e1e9314d9"'

但是如果我查看数据库,新行是存在的。

使用 mysqli_real_escape_string() 对参数进行转义:

$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);

$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ($userid, \"$msg\", \"$uniqid\", \"$link\")";
// die($sql);
$this->query($sql);

我尝试使用 $mysqli->affected_rows 和 mysqli_query() 的 !$result 检查查询执行情况。

字段类型是

INT (11) for userid, TEXT for content, TINYTEXT for uniq and TINYTEXT for link.

所有 TEXT 字段都有排序规则“utf8_general_ci”。

我没有创建表。

奇怪的是,如果我在数据库中查找,查询是成功执行的……

为什么会这样?

【问题讨论】:

  • 我猜你不需要使用escape character(\) for double quotes,如果已经使用$this->escape($msg)转义了。否则请尝试$msg = mysqli_real_escape_string($msg);
  • 如果你做$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ($userid, "$msg", "$uniqid", "$link")";,它仍然会失败吗? (删除了反斜杠)
  • sql字符串的反斜杠是因为值是用双引号插入的:"value with \"double quotes\"" 查询执行得很好(在DB中我可以读到那行),但它失败了:| $this->escape() 是 mysqli_real_escape_string() 的别名,我在说明中写了
  • 删除反斜杠会删除错误信息...
  • 反斜杠是 PHP 字符串转义,不是 SQL 的

标签: php sql mysqli sql-insert


【解决方案1】:

你的sql应该是这样的

$userid = $this->escape($userid);
$msg = $this->escape($msg);
$uniqid = $this->escape($uniqid);
$link = $this->escape($link);

$sql = "INSERT INTO notifications (userid, content, uniq, link) VALUES ('$userid', '$msg', '$uniqid', '$link')";

【讨论】:

  • 我也试过了,还是一样的错误,但是新行在数据库中仍然可读,这很奇怪
  • 我使用双引号时遇到的相同错误。但是,即使有错误,查询实际上也成功插入了数据库中。
  • 是的,仍然得到相同的错误消息,所以问题不在于引号......但是,该行实际上仍然插入到数据库中。
  • 我认为您的转义功能无法正常工作
  • $this->escape() 是 mysqli_real_escape_string() 的别名
猜你喜欢
  • 2019-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-25
  • 2014-12-03
相关资源
最近更新 更多