【问题标题】:What's the correct syntax for returning a single value using PDO and mySQL?使用 PDO 和 mySQL 返回单个值的正确语法是什么?
【发布时间】:2017-11-28 23:46:28
【问题描述】:

我正在尝试将我的 sql 切换到 PDO,但我什至无法让这个简单的查询返回一个值。当然不可能这么难。我用老式的方式完成了同样的查询,它按预期完美地工作。 PDO 版本不返回任何内容。这里有什么诀窍?

第一个版本返回我期望的值。

  $customfieldid = 676;
  $entityid = 9784549;
  $entitytype = 'familyoverview';

  $sql = "select value
                  from customfieldvalues
                 where customfieldid = ".$customfieldid."
                   and entityid = ".$entityid."
                   and entitytype = '".$entitytype."'";

  $result = mysql_query($sql);

  if($row = mysql_fetch_array($result)) {
    $mysqlvalue = $row["value"];
    echo "<br>mysql value: ".$mysqlvalue;
  }

此 PDO 版本不返回任何内容。

  $sql = "select value
                  from customfieldvalues
                 where customfieldid = :customfieldid
                   and entityid = :entityid
                   and entitytype = :entitytype";

  $stmt = $pdo->prepare($sql);
  //$stmt->bindValue(':customfieldid', $customfieldid, PDO::PARAM_INT);
  //$stmt->bindValue(':entityid', $entityid, PDO::PARAM_INT);
  //$stmt->bindValue(':entitytype', $entitytype, PDO::PARAM_STR);

  $stmt->bindValue(':customfieldid', 676, PDO::PARAM_INT);
  $stmt->bindValue(':entityid', 9784549, PDO::PARAM_INT);
  $stmt->bindValue(':entitytype', 'familyoverview', PDO::PARAM_STR);

  $pdovalue = $stmt->fetchColumn();
  echo "<br>pdo value: ".$pdovalue;

我已经确认我有一个 pdo 数据库连接。我尝试使用第三个参数并在 bindValue 调用中省略第三个参数。我也尝试过硬编码 bindValue 调用中的值与传递它们,但这些都没有任何区别。

【问题讨论】:

  • @duskwuff 是正确的,您需要调用 $stmt->execute()。但我想提供一个注释,bindValue() 是不必要的,您可以简单地将参数作为数组传递给$stmt-&gt;execute()。我不知道为什么这么多学习 PDO 的人忽略了这一点。请参阅此页面上的示例 #2:php.net/manual/en/pdostatement.execute.php
  • @BillKarwin ...但前提是您使用位置参数,并且所有这些参数都可以接受字符串。
  • 不,您可以为命名参数传递关联数组。查看我链接到的页面中的示例。什么类型都没有关系。 MySQL PDO 驱动程序始终将参数作为字符串传递。
  • 感谢比尔的提示。由于可读性,我不确定我是否喜欢这样,但这可能只是习惯它的问题。我会考虑的。

标签: php mysql pdo


【解决方案1】:

您的 PDO 代码缺少对 $stmt-&gt;execute() 的调用,因此查询永远不会发送到 MySQL 服务器并执行。如果不执行查询,就不会有任何结果。

【讨论】:

  • 谢谢!我的假设是 $stmt->fetchColumn() 代替了 execute() 调用。没有意识到我需要两者。
  • PDOStatement-&gt;fetchColumn() 更接近于mysql_fetch_array()mysql_query()本质上是PDO-&gt;prepare()PDOStatement-&gt;bindValue()PDOStatement-&gt;execute()的组合。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多