简体   繁体   English

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

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

When I execute the following code on a server that does not support get_result(), $results comes back as '1'. 当我在不支持get_result()的服务器上执行以下代码时,$ results将返回为“ 1”。 It seems that $stmt->fetch() is not working properly. 似乎$ stmt-> fetch()无法正常工作。 Is there something I am doing wrong? 我做错什么了吗?

I am using a GoDaddy Shared Hosting Account and my local server as my testing environment. 我使用GoDaddy共享主机帐户和本地服务器作为测试环境。 My local server supports get_result() so that works as intended. 我的本地服务器支持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();
}

Although PHP codebase is indeed inconsistent, there is still very little sense in having two different functions for returning the same value. 尽管PHP代码库确实不一致,但是使用两个不同的函数返回相同的值仍然没有什么意义。 So, we can conclude that fetch() returns not the same thing as get_result(). 因此,我们可以得出结论,fetch()返回的内容与get_result()不同。 Having concluded that we can verify our assumption using manual page. 得出结论,我们可以使用手册页验证我们的假设。 And find there the right usage for the fetch() 并找到fetch()的正确用法

You need to use bind result for the fetch() if this is mysqli 如果这是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 http://www.php.net/manual/zh/mysqli-stmt.fetch.php

mysqli_stmt::fetch returns a bool value and they don't accept any parameters. mysqli_stmt::fetch返回布尔值,并且它们不接受任何参数。 You can clearly see it in documentation. 您可以在文档中清楚地看到它。 If you need to pass sql statement then mysqli_stmt_fetch is your function which accepts mysqli_stmt as an argument. 如果您需要传递sql语句,则mysqli_stmt_fetch是您的函数,该函数接受mysqli_stmt作为参数。

You should use 你应该用

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

You can find more info here 您可以在这里找到更多信息

I used the following code to solve my issue: 我使用以下代码解决了我的问题:

$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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM