php - mysqli有效,但pdo没有

时间:2012-02-09 21:50:48

标签: php pdo mysqli

我正在尝试切换到pdo并享受成功,但我的最新功能将无效。然而,当我恢复到mysqli时,它很好。我确定我错过了什么,但是什么?

没有工作PDO:

$db = db_pdo();
$query = $db->prepare("select * from locks_for_sale where type_3=':search'");
$query->bindParam(":search", $sub_items[3]);
$query->execute();

if (!$result=$query->fetch()) {
    $print .= "<tr><td>&nbsp;</td><td><h3>No products currently available.</h3></td></tr>\n";
}

else {
    other code

请注意:
函数db_pdo包括在内。
$ sub_items [3]是一个字符串。

工作mysqli:

$db = db_conn();
$sql = "select * from locks_for_sale where type_3='".$sub_items[3]."'";
$query = $db->query($sql);

if (!$query->fetch_assoc()) {
    $print .= "<tr><td>&nbsp;</td><td><h3>No products currently available.</h3></td></tr>\n";
}

else {
    other code

再次包含db_conn。

我知道此查询的结果是返回2个项目,但pdo版本显示!$ result。

提前致谢。

3 个答案:

答案 0 :(得分:2)

:search参数中删除引号:

$query = $db->prepare("select * from locks_for_sale where type_3=:search");
//--------------------------------------------------------------^^^^^^^^^^

如果引用,它将被视为文字字符串':search',并且最终会出现错误,因为它会绑定不正确数量的参数。

如果您不熟悉预处理语句,请尽量不要将它们视为将变量放入SQL字符串,就像连接或插入变量时一样。相反,您将参数值直接传递到数据库引擎,而数据库引擎又将它们相应地放入查询中。使用适当的引用构建有效语句成为RDBMS的责任。

答案 1 :(得分:0)

鉴于您的00000错误代码,这实际上意味着查询成功。问题出在你的获取逻辑上:

if (!$query->fetch_assoc()) {
    ^--- remove

如果获取成功,则调用将返回not-false,即true。然后,您使用!将其反转并将其变为false,从而导致other code运行。

答案 2 :(得分:0)

尝试bindValue(http://www.php.net/manual/en/pdostatement.bindvalue.php

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindValue(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>

另见: What is the difference between bindParam and bindValue?