Fatal error: Call to a member function fetch_array () on boolean when querying function help [duplicate]

0

I am doing a function that when it receives a number, in the case, an id it makes a query and it rescues the name that is in that id and I come across this error.

code

function catporid($cat){

    global $aCon;

    $sql = 'SELECT cat_nome FROM cat WHERE cat_id = $cat';  

    $query = $aCon->query($sql);   

    $r = $query->fetch_array();    

    $cat = $r['cat_nome'];  

    return $cat."id";

}
    
asked by anonymous 14.04.2017 / 19:55

2 answers

1

Use { v keys to work with variables within quotation marks:

$sql = "SELECT cat_nome FROM cat WHERE cat_id = '{$cat}'";

Or you can also do this:

$sql = "SELECT cat_nome FROM cat WHERE cat_id = '". $cat . "'";

It is also recommending that you verify that the results of this query were returned before attempting to print or capture any value.

function catporid($cat){
    global $aCon;
    $stmt = "SELECT cat_nome FROM cat WHERE cat_id = '{$cat}'";

    if($query = $aCon->query($stmt)){
        if($query->num_rows > 0){
            $r = $query->fetch_array();
            return $r['id'];
        }
    }
    return false;
}
    
14.04.2017 / 20:21
0

According to the php documentation, MySQLi :: query ():

  

Returns FALSE on failure. For SELECT, SHOW, DESCRIBE   or EXPLAIN mysqli_query () will return an object   mysqli_result. For other successful queries mysqli_query ()   will return TRUE. This means that the following query is failing

 $mysqli->query($bup);
  

Which means that some statement in sql in a variable is causing an error. I recommend review or table test. It seems that the error is not a   syntax (since a syntax error would have caused a   even more complex error), which means that MySQL can read your   statement, but the operation is failing for some reason. You will have   which review your SQL statement as well as your table and see what the failure   in logic it is.

Source: Source 01

    
14.04.2017 / 20:05