Jump to content

How do I write a 0 count if a row doesn't exist?


Jeffro

Recommended Posts

I'm printing some mysql results to a table and sometimes I have rows with no results so they never get counted...  which results in an ugly looking parenthesis on my page with nothing it  ().  For these times, I'd like to print a zero. 

 

How can I rewrite the following to achieve this? 

 

if($row['mycount'] does not exist) {
$row['mycount'] = '0';
}

if (empty($row['mycount'])) {
  $row['mycount'] = '0';
}

Should do the trick. If the element does not exist in the array, or if it is false, null, or zero; empty() will be true.

 

You could also do it using the ternary operator in the output:

 

echo 'The count is: ' . (empty($row['mycount']) ? '0' : $row['mycount']);

Hmmm... seems like that should have worked, but it didn't seem to do anything.  When the row doesn't exist, it still won't assign a zero. 

 

Here's my full code:

 

$query = "SELECT SUBSTR(url,8,INSTR(url,'.')- as cityname, COUNT(*) as citycount FROM cities GROUP BY SUBSTR(url,8,INSTR(url,'.')-";
$result = mysql_query($query) or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($result))
{
$data[$row['cityname']] = $row['citycount'];
}

 

Later on, I'm calling the city names in my hyperlinks, like so:

<a href="/city/ausin/">Austin</a> (<?php echo $data['austin']; ?>)<br>
<a href="/city/dallas/">Dallas</a> (<?php echo $data['dallas']; ?>)<br>
<a href="/city/miami/">Miami</a> (<?php echo $data['miami']; ?>)<br>

 

This produces a result set such as: 

Austin (9)

Dallas (4)

Miami ()  <-- where () should read (0)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.