【问题标题】:PDO INSERT simple snippet that plainly doesn't work [duplicate]PDO INSERT 显然不起作用的简单片段[重复]
【发布时间】:2012-11-07 08:12:42
【问题描述】:

可能重复:
Can you put placeholders in select part of a query using PDO?

我不喜欢问这么“简单”的问题,但是这段代码不起作用,我在尝试 1 小时后无法弄清楚为什么($this->DB 工作没有问题)。

此代码不起作用:

$STH = $this->DB->prepare("INSERT INTO chapters (subject_keyword, type, ?) VALUES (?, 'Introduction', ?)");
$STH->execute(array($this->Language, str_replace(' ', '_', $Title), $Introduction));
print_r($STH->ErrorInfo());

也不是扩展形式:

$t_lang = $this->Language;
$t_title = str_replace(' ', '_', $Title);
$t_intr = $Introduction;
$STH = $this->DB->prepare("INSERT INTO chapters (subject_keyword, type, ?) VALUES (?, 'Introduction', ?)");
$STH->execute(array($t_lang, $t_title, $t_intr));
print_r($STH->ErrorInfo());

而返回的错误是:

DDC: 164Array ( [0] => 42000 [1] => 1064 [2] => 您的 SQL 语法有错误;请查看与您的 MySQL 服务器版本相对应的手册,以了解在附近使用的正确语法''en') VALUES ('Test_tittle', 'Introduction', ' \r\n 这是第 1 行的介绍 t' )

这个错误对我来说并没有什么意义,因为这几行 mysql 似乎是正确的,除了 \r\n.但我也试过做htmlentities($Introduction) 和其他一些没有运气的事情。这里的所有变量都已设置并具有一些非空值。

【问题讨论】:

  • 您能否显示您尝试插入的数据的值?
  • 列名不能使用占位符。
  • "en", "Test title" 和 "This is the introduction text."
  • 我只是想弄清楚@PeeHaa,那我该怎么做呢?使用 bindParam?
  • 不,你根本做不到。使用白名单或重新考虑您的设计。

标签: php insert pdo


【解决方案1】:

试试:

$t_lang = $this->Language;
if (!in_array($t_lang, array('en', 'jp', ... Your other languages ...))) {
    throw new Exception(... Error message ...);
}
$t_title = str_replace(' ', '_', $Title);
$t_intr = $Introduction;
$STH = $this->DB->prepare("INSERT INTO chapters (subject_keyword, type, " . $t_lang . ") VALUES (?, 'Introduction', ?)");
$STH->execute(array($t_title, $t_intr));
print_r($STH->ErrorInfo());

【讨论】:

  • 这不是容易被注入吗?
  • 这取决于你的 $t_lang 来自哪里。我还编辑了我的答案。
  • 非常正确,但它来自一个相对较长的路,我在某处读到我应该在数据库中使用它之前使其注入安全,所以我最好清理它。此外,我只是在使用这个。编辑后,我的代码看起来几乎一样 (;
猜你喜欢
  • 2018-11-14
  • 2023-03-29
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
相关资源
最近更新 更多