0

I have been trying to set a while loop to add all the ids in which the user has 20 days into an array. Currently, it displays an error of undefined offset. How can I code the code so that it first gets the id of the first row with 20 days in the lastSeen column, then, second, the ids of the second row and then adds them to the array?

$get_email = mysqli_query($con, "SELECT id FROM users WHERE lastSeen='20'" );
$email = mysqli_fetch_array($get_email);
$num_days = mysqli_num_rows($get_email);
$i = 1; 
$array_id = array();
while($i <= $num_days){
array_push($array_id, $email[$i]);
$i = $i + 1;
}
2
  • mysqli_fetch_array() does not return all the result set as you might think. The documentation says: "Fetch a result row...". This means you have to call it again and again in the loop to get all the rows. Commented Oct 21, 2017 at 7:19
  • @axiac What can I replace it with to get the intended results. Commented Oct 21, 2017 at 7:22

1 Answer 1

1

First of all, your code is confusing. You get IDs from the database but the names of the variables tell "email". Try to be consistent, it will help you later, when you read this code again.

Since you don't do any processing with the values you get from the database, you can use mysqli_fetch_all(). It returns all the rows from the record set at once in an array. Passing MYSQLI_ASSOC as its second argument tells it to use the column names (from the SELECT clause of the query) as keys in the arrays it creates from each row of the result set.

Next, the PHP function array_column() extracts only the values of column id into a new array that contains exactly the values you need:

$result = mysqli_query($con, "SELECT id FROM users WHERE lastSeen='20'");
// Get all the rows, indexed by column names
$rows   = mysqli_fetch_all($result, MYSQLI_ASSOC);
// Get only the 'id' column
$ids    = array_column($rows, 'id');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.