ERROR: Call to a member function fetch_assoc () on a non-object in

0

I have the following code in php but it sends me a fatal error: Call to a member function fetch_assoc () on a non-object in /public_html/gcm/run.php on line 46r, despite that the script apparently works, How could I solve it, I'm sending the code:

 $sql = "SELECT gcm_regid  FROM gcm_users WHERE papa1 = '$papa1'  AND  cel1 = '$cel1'"; 
 echo $sql; 
 $result = $conn->query($sql); 
 if ($result->num_rows > 0) { 
 while($row = $result->fetch_assoc()) { 
  include_once '../gcm/GCM.php'; 
$regId = $row["gcm_regid"]; 
$message = $message; 
echo $regId; 
echo $message; 
echo "entre"; 
$gcm = new GCM(); 
$registatoin_ids = array($regId); 
$message = array("price" => $message); 
$result = $gcm->send_notification($registatoin_ids, $message); 
echo $result; 
} 
}else{ 
 echo "0 results"; 

} 
$conn->close();  
    
asked by JESUS ESPINOSA 12.02.2016 в 15:00
source

1 answer

2

The error "Call to a member function <función> on a non-object in" happens because the variable, in this case $result , is not an object and therefore the expected method or function can not be called. This is best explained here (English language) .

The problem is in this line within while :

$result = $gcm->send_notification($registatoin_ids, $message);

You are overwriting the variable $result . It is very likely that the new value of $result is not that of executing $conn->query($sql) , therefore the error. I recommend you use another name for this local variable in the cycle while .

This is not the real problem, but mostly it is the cause. I leave it indicated in case someone comes across this problem because of the query.

When mysqli_query has an error processing the SQL statement it has, returns falso (emphasis mine):

  

Return values

     

Returns FALSE in case of error. If a query of type SELECT , SHOW , DESCRIBE or EXPLAIN is successful, mysqli_query() will return an object mysqli_result . For other successful queries of mysqli_query() you will return TRUE .

The query may return false . It is very likely that the problem is here:

$sql = "SELECT gcm_regid  FROM gcm_users WHERE papa1 = '$papa1'  AND  cel1 = '$cel1'";

This can happen because you directly concatenate the values of $papa1 and $cel1 in your query, and may have characters that break the query. Here is an example:

$papa1 = "papa";
$cel1 = "cel'"; //nota la comilla al final
$sql = "SELECT gcm_regid  FROM gcm_users WHERE papa1 = '$papa1'  AND  cel1 = '$cel1'";
echo $sql;

What will you print:

SELECT gcm_regid  FROM gcm_users WHERE papa1 = 'papa' AND cel1 = 'cel''

And voalá, query destroyed: D

To avoid cleaning the values of these variables in this and other queries, I recommend you execute the query in a prepared manner, as I explained in this other answer .

    
answered by 12.02.2016 / 15:22
source