Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use mysql_fetch_array() with foreach() instead of while()

Tags:

php

i want to know how do we convert the following code to work with foreach

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;"; 

    $result_select = mysql_query($query_select) or die(mysql_error());

    while($row = mysql_fetch_array($result_select)) {
        $ename = stripslashes($row['name']);
        $eemail = stripcslashes($row['email']);
        $epost = stripslashes($row['post']);
        $eid = $row['id'];

        $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

        echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

        echo $eid . '<br/>';

        echo $ename . '<br/>';

        echo $eemail . '<br/>';

        echo $epost . '<br/><br/><br/><br/>';
like image 798
Ibrahim Azhar Armar Avatar asked Aug 09 '10 18:08

Ibrahim Azhar Armar


2 Answers

You can code like this:

$query_select = "SELECT * FROM shouts ORDER BY id DESC LIMIT 8;";
$result_select = mysql_query($query_select) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_array($result_select))
    $rows[] = $row;
foreach($rows as $row){ 
    $ename = stripslashes($row['name']);
    $eemail = stripcslashes($row['email']);
    $epost = stripslashes($row['post']);
    $eid = $row['id'];

    $grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5(strtolower($eemail))."&size=70";

    echo ('<img src = "' . $grav_url . '" alt="Gravatar">'.'<br/>');

    echo $eid . '<br/>';

    echo $ename . '<br/>';

    echo $eemail . '<br/>';

    echo $epost . '<br/><br/><br/><br/>';
}

As you can see, it's still need a loop while to get data from mysql_fetch_array

like image 195
Bang Dao Avatar answered Sep 21 '22 06:09

Bang Dao


There's not a good way to convert it to foreach, because mysql_fetch_array() just fetches the next result from $result_select. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:

$result_list = array();
while($row = mysql_fetch_array($result_select)) {
   result_list[] = $row;
}

foreach($result_list as $row) {
   ...
}

But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array() works. Why is it so important to use a foreach()?

EDIT: If this is just for learning purposes: you can't convert this to a foreach. You have to have a pre-existing array to use a foreach() instead of a while(), and mysql_fetch_array() fetches one result per call - there's no pre-existing array for foreach() to iterate through.

like image 31
cincodenada Avatar answered Sep 19 '22 06:09

cincodenada