简体   繁体   中英

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'. It seems that $stmt->fetch() is not working properly. Is there something I am doing wrong?

I am using a GoDaddy Shared Hosting Account and my local server as my testing environment. My local server supports get_result() so that works as intended.

$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. So, we can conclude that fetch() returns not the same thing as get_result(). Having concluded that we can verify our assumption using manual page. And find there the right usage for the fetch()

You need to use bind result for the fetch() if this is mysqli

 /* 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 returns a bool value and they don't accept any parameters. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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