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';
}

Link to comment
Share on other sites

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']);

Link to comment
Share on other sites

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)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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