making an IF statement in php/mySQL

He has: 688 posts

Joined: Feb 2001

Simple question. I have a bit of code which prints the number of entries matching a specified field entry. This example is for how many people have NJ (New Jersey) in their state field:

<?php
$query
= \"SELECT COUNT(*) FROM alumni WHERE state='NJ'\";
                       
$result = mysql_query( $query );
                       
$totalEntries = mysql_result( $result, 0 );
                        print \"<p>\".
$totalEntries.\"</p>\n\";
?>

How do I make this an IF statement, so it does the same thing if there is at least one matching entry, but will not print anything if the result is zero. (Right now it prints "0" if there are no matching entries.)

Thanks in advance. Smiling

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

<?php
if ($totalEntries > 0) print \"<p>\".$totalEntries.\"</p>\n\";
?>

More advanced for if you need soemthing else:
<?php
if ($totalEntries > 0)
{
    print \
"<p>\".$totalEntries.\"</p>\n\";
}
else
{
    // do something else here
}
?>

He has: 698 posts

Joined: Jul 2005

Or, if you want a 1 character longer code...Sticking out tongue

<?php

$query
= \"SELECT COUNT(*) FROM alumni WHERE state='NJ'\";
                       
$result = mysql_query( $query );
                       
$totalEntries = mysql_result( $result, 0 );
if (
$totalentries >= \"1\") {
                        print \"<p>\".
$totalEntries.\"</p>\n\";
}

?>

and like Greg K. said, you could add an else statement to be displayed if there are 0 results, like this.

<?php

$query
= \"SELECT COUNT(*) FROM alumni WHERE state='NJ'\";
                       
$result = mysql_query( $query );
                       
$totalEntries = mysql_result( $result, 0 );
if (
$totalentries >= \"1\") {
                        print \"<p>\".
$totalEntries.\"</p>\n\";
} else {
print \"<p>There were no entries found.</p>\n\";
}

?>

Kurtis

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.