PDO结果为空

时间:2016-08-30 10:11:40

标签: php mysql mysqli pdo

我决定从mysqli / mysqlnd转到PDO,但是我遇到的问题是我上一次这样做了。我再次尝试这个,因为似乎PDO似乎支持将包含值数组的变量传递给execute() param以绑定到查询而不必使用call_user_func_array之类的东西。

我演示的代码是:

$bind_arguments[] = "dogs";
$bind_arguments[] = "cats";
$bind_arguments[] = "birds";

$db = new PDO('mysql:dbname=' . SQL_DATA . ';host=' . SQL_SERVER, SQL_USERNAME, SQL_PASSWORD, array (
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)); 

$sql = 'SELECT `name` FROM `pets` WHERE `type` = ? OR `type` = ? OR `type` = ?';

$result = Array();
try {

    if($stmt = $db->prepare($sql)) {

        $stmt->execute($bind_arguments);
        $result = $stmt->fetchAll();


    }
} catch(PDOException $e) {
    echo 'Wrong SQL: ' . $sql . ' Error: ' . $e->getMessage(); exit;
}

$db = null;

var_export($result);  // null

我没有任何例外,但$result为空。如果我使用Navicat进行常规查询(或使用mysqli)它可以工作!

请参阅Example #5,其中显示我应该可以执行此操作(从此处发布示例以供参考):

<?php
/* Execute a prepared statement using an array of values for an IN clause */
$params = array(1, 21, 63, 171);
/* Create a string for the parameter placeholders filled to the number of params */
$place_holders = implode(',', array_fill(0, count($params), '?'));

/*
    This prepares the statement with enough unnamed placeholders for every value
    in our $params array. The values of the $params array are then bound to the
    placeholders in the prepared statement when the statement is executed.
    This is not the same thing as using PDOStatement::bindParam() since this
    requires a reference to the variable. PDOStatement::execute() only binds
    by value instead.
*/
$sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)");
$sth->execute($params);
?>

另请参阅下面的Example #1以方便:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>

那为什么这不起作用?我做错了什么?

更新

我在发布StackOverflow's MVCE要求的代码(从较大的类中删除)时发了一些错别字。原始类中没有这些拼写错误。我在上面的代码中更新了它们。 - 对不起这可能导致的任何混淆。

1 个答案:

答案 0 :(得分:1)

您要将值分配给$bind_array$bnid_array,但是会将$bind_arguments发送给execute()。尝试将$bnid_array更改为$bind_array并使用$stmt->execute($bind_array);