Page 1 of 1

How to NOT display empy db columns

Posted: Thu Mar 31, 2011 8:55 pm
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~

Re: How to NOT display empy db columns

Posted: Fri Apr 01, 2011 10:10 am
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