Guys I have this PHP code :
<?php
foreach ($user as $u){
$sql = " Select Token From notification_data where user_id='$u';";
$result = mysqli_query($con,$sql);
$tokens = array();
if(mysqli_num_rows($result) > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
array_push($tokens, $row["Token"]);
}
}
mysqli_close($con);
$notification = array(
'title' => "New ticket!!",
'body' => "A new tournament is ready, Join now or miss out"
);
foreach ($tokens as $t ) {
sendNotif($t, $notification);
}
}
?>
Where I put an array of users_id, then take the user_id one by one and send them notifications.
This code works fine for the first loop the notification gets sent successfully, but after that I get these errors for every loop :
Warning: mysqli_query(): Couldn't fetch mysqli
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in ..
Warning: mysqli_close(): Couldn't fetch mysqli in ..
Hope you can help me guys I’m new to PHP and I didn’t know how to solve this.
>Solution :
You are closing your MySQL connection inside the loop .. It is obviously opened above the loop as it is set here $result = mysqli_query($con,$sql); So it WILL run the first time, until it hits the "close", and then it will no longer be able to access the $con object.
Move the "close" mysqli_close($con); outside the loop