Jump to content

PHP foreach function and getting data from MySql


MP145

Recommended Posts

Let me explain what i am trying to accomplish here. I am trying to get image data from a table in MySql and display it on my page. There are 5 rows of images in the database table, my code is as follow;

<?php

$db="news";
$link = mysql_connect("localhost","xxx","yyyy");
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
$result = mysql_query( "SELECT image1, image2, image3, image4, image5 FROM newsitem WHERE newsID=6" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);

while ($get_info = mysql_fetch_row($result)){

foreach ($get_info as $field)

print "<img src=\"images/news/$field\"><br>";

}

mysql_close($link);
?>

It displays the image but what i want is how to stop displaying when there is no image.

 

Not all the 5 image rows has data in it, now what i get is, just say there is data (imagename) on 2 rows ie. image1 and image2 where else the rest 3 does not have data in it. The code above prints <img src> for all the 5 images with and without data, which makes the X mark appear on the display page when there is no data (imagename)

 

Should i use and if or elseif statement ? How can i do it?

Link to comment
Share on other sites

OK, i am not sure if this is the right way but it seems like working. I just added the if statement

 

<?php

$db="news";
$link = mysql_connect("localhost","root","kannan");
if (! $link)
die("Couldn't connect to MySQL");
mysql_select_db($db , $link)
or die("Couldn't open $db: ".mysql_error());
$result = mysql_query( "SELECT image1, image2, image3, image4, image5 FROM newsitem WHERE newsID=6" )
or die("SELECT Error: ".mysql_error());
$num_rows = mysql_num_rows($result);

while ($get_info = mysql_fetch_row($result)){

foreach ($get_info as $field)

if (!empty($field)) {
print "<img src=\"images/news/$field\"><br>";
}

}

mysql_close($link);
?>

 

Is this the correct way of doing it?

Link to comment
Share on other sites

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.