【问题标题】:MySQLi queries with php - query strings contain single quotes and curly bracesMySQLi 使用 php 查询 - 查询字符串包含单引号和花括号
【发布时间】:2015-05-31 10:55:01
【问题描述】:

我正在编写一个 php 脚本来将字典文件放入 Mysql 数据库。它工作正常,除非在某些情况下定义字符串包含单引号和多组花括号。这是失败的定义字符串之一。

(n) (1) {sports} 将球带回自己的手中 位置(橄榄球)/(2){econ}结转/结转扣除或 从上一年贷记到本年度(以减少所得税)

这是 **MySQLi ** 错误消息:

您的 SQL 语法有错误;检查手册 对应于您的 MySQL 服务器版本,以便使用正确的语法 near 自己的位置(橄榄球)/(2) econ', {'(n) (1) {sports} 在第 1 行带回/带上 '

下面是关于定义字符串的脚本部分:

$definition = substr($definition_string, 0, $pos);

$definition = substr($definition, 1);

// Escape single quote
$definition = str_replace(["'"], "''" , $definition);

$mysqli->set_charset("utf8");

$result = $mysqli->query("INSERT INTO dict (entry, reading, category, definition, entry_number) VALUES ('$entry', '$reading', '$category', '$definition', '$entry_number')");   

我不知道为什么它会失败并且错误消息没有多大帮助。有什么想法吗?

【问题讨论】:

  • 了解准备好的报表。
  • mysqli_real_escape_string 可以帮助你
  • 将表定义添加到问题以及生成和失败的确切生成的 sql(只是回显它)。

标签: php mysql mysqli


【解决方案1】:

我建议您阅读此here。他们提供了几种不同的方法来保护进入数据库的数据。

这是众多方法之一:

$result = $mysqli->query("INSERT INTO dict (entry, reading, category, definition, entry_number) VALUES (
'" . $mysqli->escape_string($entry) . "',
'" . $mysqli->escape_string($reading) . "',
'" . $mysqli->escape_string($category) . "',
'" . $mysqli->escape_string($definition) . "',
'" . $mysqli->escape_string($entry_number) . "')");

另一个更有说服力的解决方案:

$stmt = $mysqli->prepare("INSERT INTO dict (entry, reading, category, definition, entry_number) VALUES (
?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $entry, $reading, $category, $definition, $entry_number);
$stmt->execute();
$result = $stmt->get_result();

【讨论】:

  • 谢谢!现在完美运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 2022-01-13
  • 1970-01-01
相关资源
最近更新 更多