How to NOT display empy db columns

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
User avatar
robynprivette
Forum Commoner
Posts: 46
Joined: Sun May 02, 2010 6:22 pm

How to NOT display empy db columns

Post by robynprivette »

Ok... here's the thing. my users fill out a form but don't have to fill out every box. IF they don't, however, the display page shows broken images.

Here is the display code:

Code: Select all

// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM creatures ORDER BY RAND() LIMIT 100")
or die(mysql_error());  

while($row = mysql_fetch_array( $result )) {
// Print out the contents of the entry
echo "<a href=\"http://magistream.com/creature/".$row['code1'] ."\"><img src=\"http://magistream.com/img/" .$row['code1'] .".gif\"/></a> ";
echo "<a href=\"http://magistream.com/creature/".$row['code2'] ."\"><img src=\"http://magistream.com/img/" .$row['code2'] .".gif\"/></a> ";
echo "<a href=\"http://magistream.com/creature/".$row['code3'] ."\"><img src=\"http://magistream.com/img/" .$row['code3'] .".gif\"/></a> ";
echo "<a href=\"http://magistream.com/creature/".$row['code4'] ."\"><img src=\"http://magistream.com/img/" .$row['code4'] .".gif\"/></a> ";
}
?>
And I'm not great with coding so if you could please show me how to do it using my code. Thanks~
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: How to NOT display empy db columns

Post by social_experiment »

Im not sure if there is a function (in sql or php) that checks for an empty column value but you could try check if a value is contained before printing the image.

Code: Select all

// other code - inside your while loop.
for ($i = 1; $i <= $yourAmountOfFields; $i++) {
  $value = 'code';
  $field = $value.$i;
  if ($row[$field] != '') {
   echo "<a href=\"http://magistream.com/creature/".$row[$field] ."\">
<img src=\"http://magistream.com/img/" .$row[$field] .".gif\"/></a> ";
  }
}
This is dependant on your field names. I am guessing that there are only 4 (from your sample code : code1, code2, etc). You assign the name part of the field name (code) to a variable the in the following line you add the value of the incrementer ($i). Next you check if the field contains data, and if it does, the image code is printed.
Hth
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply