11

Ok, So I am trying to query my database and select all rows that have a certain value. After that I turn the query into an array with mysql_fetch_array(), then I tried iterating by row through the fetched array using a for each loop.

<?php
$query = mysql_query("SELECT * FROM users WHERE pointsAvailable > 0 ORDER BY pointsAvailable Desc");
$queryResultArray = mysql_fetch_array($query);
foreach($queryResultArray as $row)
{
    echo $row['pointsAvailable'];
}
?>

Though when I do this for any column besides the pointsAvailable column say a column named "name" of type text it only returns a single letter.

How do I iterate through a returned query row by row, and be allowed to fetch specific columns of data from the current row?

3 Answers 3

30
$result = mysql_query("SELECT id, name FROM mytable");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
    printf("ID: %s  Name: %s", $row[0], $row[1]);  
}

or using MYSQL_ASSOC will allow you to use named columns

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    printf("ID: %s  Name: %s", $row["id"], $row["name"]);
}
2
  • Thank you worked perfectly. So does it actually just return one row each time mysql_fetch_array is called on the query resource?
    – AFK
    Feb 18, 2010 at 1:15
  • Each time mysql_fetch_array is called, it returns the current row and moves the data pointer ahead to the next row. When all rows are traversed, it returns false and the while loop ends.
    – Trevor
    Feb 18, 2010 at 1:18
0

Yes using mysql_fetch_array($result) is the way to go.

0

With PHP 7+ becoming the new standard and mysql_fetch_array becoming deprecated you will need to start using mysqli_fetch_array.

Object-oriented style

$result = $mysqli->query($query);
/* numeric array */
while ($row = $result->fetch_array(MYSQLI_NUM)) {
    // Do stuff with $row
}
/* associative array */
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
    // Do stuff with $row
}
/* associative and numeric array */
while ($row = $result->fetch_array(MYSQLI_BOTH)){
    // Do stuff with $row
}

Procedural style

$result = mysqli_query($mysqli, $query);
/* numeric array */
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
    // Do stuff with $row
}
/* associative array */
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
    // Do stuff with $row
}
/* associative and numeric array */
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
    // Do stuff with $row
}

You can read more about this change on the PHP Bible..

https://www.php.net/manual/en/mysqli-result.fetch-array.php

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.