【问题标题】:Mysqli to PDO binding parametersMysqli 到 PDO 绑定参数
【发布时间】:2017-04-03 12:47:13
【问题描述】:

我正在从 mysqli 语法切换到 PDO 并且有一些疑问:

在我使用这个之前(绑定int、字符串、十进制值的例子):

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, id, value) VALUES (?, ?, ?)");
$stmt->bind_param("sid", $firstname, $id, $value);
$stmt->execute();

使用 PDO 我应该使用这个:(这里 param decimal 已经不存在,更不用说我必须为 binging 写多行)

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, id, value) VALUES (?, ?, ?)");
$stmt->bindParam(1, $firstname, PDO::PARAM_STR);
$stmt->bindParam(2, $id, PDO::PARAM_INT);
$stmt->bindParam(3, $value, PDO::PARAM_STR);//no decimal type!
$stmt->execute();

我应该“忘记”类型并这样做吗?

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, id, value) VALUES (?, ?, ?)");
$stmt->execute([$firstname, $id, $value]);

这种情况下 int 和 decimal 怎么会失败?

【问题讨论】:

  • 事物 PDO::PARAM_ 更多地用于(不仅)生成带或不带引号的正确 sql 查询。浮点数/小数不能像整数2 那样输入,它们必须在实际执行的查询中加上'1.1' 之类的引号,所以使用PDO::PARAM_STR 就可以了。或者像你说的那样忘记它,只使用execute()。

标签: php mysqli pdo bind


【解决方案1】:

是的,大多数时候你应该这样做。

只有few extremely rare cases,您必须在其中摔倒才能分开绑定。而对于 INT 和 DECIMAL 字符串绑定都可以。

请注意,对于小数类型,您也应该在 mysqli 中使用“s”。

【讨论】:

  • 如果我自己将它们强制执行会怎样? $stmt -> 执行([$firstname, intval($id), floatval($value)]);
  • 你可以,但不会有任何区别。
  • "请注意,对于十进制类型,您也应该在 mysqli 中使用 "s"。"它在这里说“d”:php.net/manual/en/mysqli-stmt.bind-param.php
  • @Toniq 那里看不到小数点。它说双
猜你喜欢
  • 2013-05-21
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 2015-10-01
  • 2016-06-29
  • 1970-01-01
  • 2010-12-03
  • 2012-08-04
相关资源
最近更新 更多