PHP MySQLi准备的语句fetch()返回';1';而不是查询的结果


PHP MySQLi prepared statement fetch() returns '1' instead of result from query

当我在不支持get_result()的服务器上执行以下代码时,$results返回为'1'。$stmt->fetch()似乎工作不正常。我做错什么了吗?

我使用GoDaddy共享托管帐户和我的本地服务器作为我的测试环境。我的本地服务器支持get_result(),以便按预期工作。

$stmt = self::$conn->prepare($sql);
$ex = $stmt->execute();
$stmt->store_result();
if (method_exists($stmt, 'get_result'))
{
    $results = $stmt->get_result();
}
else
{
    $results = $stmt->fetch();
}

尽管PHP代码库确实不一致,但使用两个不同的函数返回相同的值仍然没有什么意义。因此,我们可以得出结论,fetch()返回的内容与get_result()不同。得出结论,我们可以使用手册页面验证我们的假设。找到fetch()的正确用法

如果这是mysqli ,则需要为fetch()使用绑定结果

 /* bind result variables */
    $stmt->bind_result($name, $code);
    /* fetch values */
    while ($stmt->fetch()) {
        printf ("%s (%s)'n", $name, $code);

http://www.php.net/manual/en/mysqli-stmt.fetch.php

mysqli_stmt::fetch返回布尔值,它们不接受任何参数。您可以在文档中清楚地看到它。如果您需要传递sql语句,那么mysqli_stmt_fetch就是您的函数,它接受mysqli_stmt作为参数。

你应该使用

 $stmt->bind_result($field1, $field2);
    while($stmt->fetch()){
     $result[] = array($field1,$field2);
    }

您可以在这里找到更多信息

我使用以下代码来解决我的问题:

$stmt = self::$conn->prepare($sql);
$ex = $stmt->execute();
$stmt->store_result();
$results = array();
$allResults = array();
$params = array();
$meta = $stmt->result_metadata();
if ($meta)
{
    while ($field = $meta->fetch_field())
    {
        $allResults[$field->name] = null;
        $params[] = &$allResults[$field->name];
    }
    call_user_func_array(array($stmt, 'bind_result'), $params);
}
while ($stmt->fetch())
{
    $results[] = $allResults;
}
$stmt->free_result();