Jump to content

Recommended Posts

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.

 

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

Link to comment
https://forums.phpfreaks.com/topic/125867-foreach-not-looping-through-all-data/
Share on other sites

Your foreach(..) loop loops through each column in the row, but the $result->fetch_array(...) only grabs one row at a time from the result source.  You need to wrap all that in a loop; example:

 

while ($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>';
   }
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.