0

Is there a way to make the code below cleaner? I wanted to access the rows of $query4week like this: $query4week[0]. But mysqli_query() returns an Object on which I don't know how to access its particular rows. So, using fetch_array and a for loop I decided to create my own index.

$sql2 = "SELECT * FROM meals ORDER BY RAND() LIMIT 7";
$query4week = mysqli_query($con, $sql2) or die(mysqli_error($con));
for ($i = 0; $result = mysqli_fetch_array($query4week, MYSQLI_ASSOC); $i++)
{
    $meal4week[$i] = $result['meal'];
}

I am still learning PHP and yet quite weak with OOP topics, please be patient :-)

4 Answers 4

1

Do it in this way

$i = 0; 
while ($result = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
    $meal4week[$i] = $result['meal'];
    $i++;
}

should work.

Sign up to request clarification or add additional context in comments.

Comments

1

You shouldn't need a for loop if your fetching an associative array.

$i = 0;
while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC))
{
    $meal4week[$i] = $row['meal'];
    $i++;
}

3 Comments

If missed the ; the first time too after $i++, badly copy&pasty ;)
@justacoder fixed ¯\_(ツ)_/¯ I had gone back to fix quotes in my typing, no copy pasta here.
No more missing, just an add to your response ;)
1

There are already some perfectly reasonable answers here, but this is a little long for a comment. If all you are creating is a numerically indexed array starting with index 0, you don't need to explicitly define the index.

while($row = mysqli_fetch_array($query4week, MYSQLI_ASSOC)) {
    $meal4week[] = $row['meal'];
}

should work just fine. No $i necessary.

3 Comments

Thank you very much for your answer - this is a good alternative and would surely make the code cleaner. But I think @ZeissS answer helps me most, as I wasn't sure if I am doing something over-complicated or if there is an other fetch function which does all that at once.
That makes sense, that answer is a better explanation. There actually is another fetch function which does it all at once (fetch_all), but as noted in the linked doc, it is available for MySQL Native Driver Only.
Another option if you want a fetch_all is to use pdo rather than mysqli. But fetching in a while loop is a pretty minor thing to do, and depending on your result set, often a better option anyway.
0

mysqli_query returns you a resource which represents the query result. You need to use the mysql_fetch_* functions to iterate over the result row by row. So yes, you need some kind of loop, if you are interested in more than the first row.

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.