MP145 Posted October 21, 2008 Share Posted October 21, 2008 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 https://forums.phpfreaks.com/topic/129359-php-foreach-function-and-getting-data-from-mysql/ Share on other sites More sharing options...
MP145 Posted October 21, 2008 Author Share Posted October 21, 2008 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 https://forums.phpfreaks.com/topic/129359-php-foreach-function-and-getting-data-from-mysql/#findComment-670629 Share on other sites More sharing options...
Bendude14 Posted October 21, 2008 Share Posted October 21, 2008 if it works then stick with it... There is more than one way to skin a rabit.. Link to comment https://forums.phpfreaks.com/topic/129359-php-foreach-function-and-getting-data-from-mysql/#findComment-670631 Share on other sites More sharing options...
MP145 Posted October 21, 2008 Author Share Posted October 21, 2008 Agreed Link to comment https://forums.phpfreaks.com/topic/129359-php-foreach-function-and-getting-data-from-mysql/#findComment-670635 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.