Pranay Prakash
Pranay Prakash

Reputation: 368

How to perform a function for every row in a mysql array?

UPDATE: I solved it using a for loop:

for ($i=0; $i < mysql_num_rows($result); $i++) { 
$row = mysql_fetch_assoc($result);
echo $row['name'];
}

ORIGINAL QUESTION:

This looks kinda stupid. I'm sure im missing something that's very simple, since I was able to accomplish this before. Anyways, I want to echo some text for every item in an array. This array is derived from mySQL.

here's the code

while ($row = mysql_fetch_assoc(mysql_query("SELECT * FROM files"))) {
echo $row['name'];
}

Upvotes: 1

Views: 725

Answers (3)

Mansoor Jafar
Mansoor Jafar

Reputation: 1488

From your question it seems so simple, try this way it's working.

    $sql="SELECT name From files";
    $names = $db->query($sql);
    while($name1 = $db->fetchByAssoc($names))
    {
        echo $name1['name'];
    }

Upvotes: 0

Hkachhia
Hkachhia

Reputation: 4539

You can execute query individual instead of while loop because if your query return more than 1 rows it will goes under the loop. show your loop print only first data of result and your loop is infinite.

Upvotes: 0

Jelmer
Jelmer

Reputation: 2693

can you post the complete code? I think you forgot the database connection.

Try this:

    $result = mysql_query("SELECT * FROM files") or die (mysql_error());
    while ($row = mysql_fetch_assoc($result)) {
        var_dump($row['name']);
    }

This will throw an error, I guess you made a mistake over there. Also, var_dump() your $row in the while to make 100% sure you have "a" value.

Also, are you sure the row does exist? If don't have any records, the echo on your $row will not work sinc it does not exist.

Also, set error reporting to E_ALL like so.

    error_reporting(E_ALL);

Also, since you are running your query inside the while() loop, it will continue to run forever. So first run the query, and put it in a variable, and then loop through the results. (see my piece of code above)

Upvotes: 1

Related Questions