Hi,

I'm new to php so I'll probably be posting a few queries along the way.

The problem I'm having is I'm trying to print out an address in an HTML table with information taken from a database. The fields are Address1, Address2, Address3, Address4 and Postcode. Everything prints correctly but as there is no value in the Address2 field an extra comma appears after where the data would have been.

My question is, how do I stop this comma from printing if a field is empty?

<?php
include 'connect.php';

// Execute the SQL query and return records

$result = mysql_query("SELECT * FROM tablename WHERE id = 1234");

while ($row = mysql_fetch_array($result)) {
echo "<table width=\"75%%\" align=\"center\" cellpadding=\"0\" cellspacing=\"2\">\n";
echo "  <tr>\n";
echo "    <td width=\"75%\" class=\"infoname\">".$row{'Name'}." <img src=\"../images/1234.gif\" width=\"72\" height=\"20\"></td>\n";
echo "    <td width=\"25%\"  class=\"infotext\">&nbsp;</td>\n";
echo "  </tr>\n";
echo "  <tr>\n";
echo "    <td width=\"75%\" class=\"infotext\">".$row{'Address1'}.", ".$row{'Address2'}.", ".$row{'Address3'}.", ".$row{'Address4'}.",  ".$row{'Postcode'}.",</td>\n";
echo "  </tr>\n";
echo "</table>";
}
?>

Hope you can help.

Recommended Answers

All 2 Replies

i was little confused as to why you had 4 address field, but i think this might work. i haven't been able to test it.

<?php
include 'connect.php';

// Execute the SQL query and return records

$result = mysql_query("SELECT * FROM tablename WHERE id = 1234");

while ($row = mysql_fetch_assoc($result)) {
echo "<table width=\"75%%\" align=\"center\" cellpadding=\"0\" cellspacing=\"2\">\n";
echo " <tr>\n";
echo " <td width=\"75%\" class=\"infoname\">".$row['Name']." <img src=\"../images/1234.gif\" width=\"72\" height=\"20\"></td>\n";
echo " <td width=\"25%\" class=\"infotext\">&nbsp;</td>\n";
echo " </tr>\n";
echo " <tr>\n";
$i = 1;
$addr = '';
while( $i < 5 ) {
	$str   = $row["Address{$i}"];
	if ( !empty( $str ) ) {
		$addr .= "{$str},";
	}
$i++;
}
echo " <td width=\"75%\" class=\"infotext\">" . $addr . ", ".$row['Postcode'].",</td>\n";
echo " </tr>\n";
echo "</table>";
}
?>

Hi,

Thanks for the quick reply.

I have tested your code and it works perfectly. Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.