Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

first foreach loop works fine but after that I get these errors for every loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading