foreach not looping through all data

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
neridaj
Forum Commoner
Posts: 40
Joined: Fri Jan 05, 2007 9:55 pm

foreach not looping through all data

Post by neridaj »

Hello,

I'm trying to loop through a table to retrieve a specific field for all records in the table but my script is only returning the data for the first entry in the table. I've used this script before but I guess I'm missing something.

Code: Select all

 
function get_projects()
{
    // if(!valid_project_name($_GET['pn']))
    //  die("Invalid project name!");
    // else
    $projectname = $_GET['pn'];
    // connect to db
    $mysqli = new mysqli('host', 'user', 'pass', 'db');
    
    if(mysqli_connect_errno()) {
        printf('Connection failed: %s\n', mysqli_connect_error());
        exit();
    }
    echo '<table align="center" bgcolor="#cccccc" border="0" cellpadding="0" cellspacing="0" width="100%">';
    // query poject info
    if($result = $mysqli->query("SELECT * FROM websites")) {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        foreach($row as $key=>$value) {
            $img = strtolower(str_replace(" ", "", $row['siteName'])) .'.jpg';
                                    echo '<tr><td><img class="floatright" src="images/'. $img .'"></td></tr>';
        }
    // free result set
    $result->close();
    }
    echo '</table>';
    // var_dump($row);
    $mysqli->close();
}
 
Thanks for any help,

Jason
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: foreach not looping through all data

Post by VladSun »

Code: Select all

result->fetch_array(MYSQLI_ASSOC);
This line fetches only one row. You need a while loop to fetch all the rows.
There are 10 types of people in this world, those who understand binary and those who don't
Post Reply