Reputation: 308
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;
}
Upvotes: 0
Views: 132
Reputation: 72177
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');
Upvotes: 1