Problem with return of PHP’s Mysqli class fetch_all method

Asked

Viewed 166 times

1

So, I’m doing the maintenance of a very large system. I have the query:

$query = $mysqli->query("SELECT*FROM tabela");

And the problem is they used fetch_all() to return the data. When the query does not return records the method fetch_all() is not defined in the class mysqli_result. Therefore when the query does not return records and I try to call it, I have the Warning undefined method.

I used to do something like:

$resultado = $query->num_rows > 0 ? $query->fetch_all() : array();

this makes it $resultado turn a blank array if the query has no records returned. The problem is that many lines of code must be edited. Is there any way to "create" this method fetch_all() on the object and make it return a blank array if the query does not return records? (same or any other alternative).

@Edit

I found out that the mysqlnd. But the question follows: how to do the fetch_all() be called even if it does not exist?

Grateful

  • 1

    The fetch_all() will not work if the query has any error, if there is nothing it works normal but does not return records.

  • Thank you. I looked for why I am making a mistake and it is because mysqlnd is missing from the server. I will edit the question.

  • Change the fetch_all() for fetch_array() is very complicated?

  • In this situation yes, because thousands of lines should be changed. :/

  • What do you mean? has many calls from fetch_all()?

  • Exactly that.

  • And ask for hosting to install mysqlnd is possible?

Show 2 more comments

1 answer

1


I got it this way:

<?php

class MySQLiConnector extends \mysqli
{
    function __construct($host, $user, $pass, $db)
    {
        parent::__construct($host, $user, $pass, $db);
    }

    public function query($query) {
        if( !$this->real_query($query) ) {
            throw new exception( $this->error, $this->errno );
        }

        return new MySQLiResultSet($this);
    }
}

class MySQLiResultSet extends \MySQLi_Result
{
    public function fetch()
    {
        return $this->fetch_assoc();
    }

    public function fetch_all()
    {
        $rows = array();
        while($row = $this->fetch())
        {
            $rows[] = $row;
        }
        return $rows;
    }
}

and I started instantiating my Mysqliconnector class instead of mysqli in my connection object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.