Paolo Sartorio
Paolo Sartorio

Reputation: 11

MYSQL row count is NULL but I need to display 0

I have a simple row count in PHP. When no rows are found, I need $sfideRicevute to be '0', but this query returns me nothing.

PHP:

<?php
    $sql = "SELECT * FROM `match` WHERE show_id = $showid AND w02 = $id AND status = 'sfida'";

    if ($result = mysql_query ("$sql")){
        while ($row=mysql_fetch_array ($result)) {

?>
<? $sfideRicevute = mysql_num_rows($result); ?>
<? echo $sfideRicevute; ?>

Thanks for helping

Upvotes: 1

Views: 700

Answers (3)

Arie
Arie

Reputation: 680

From PHP docs what mysql_num_rows returns:

The number of rows in a result set on success or FALSE on failure.

It should be returning 0, if it isn't, there's likely something wrong with the query.

Also note that using these mysql_ functions are not recommended, since they are going to be removed from php, see https://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated

Second: have you thought about SQL injections, as you are putting a variable into the query directly, which also isn't recommended and not necessary with the alternatives mentioned in the link above.

Upvotes: 2

Digitalis
Digitalis

Reputation: 570

echo intval($sfideRicevute);

or

echo (int) $sfideRicevute

Both cast the value to integer 0. In php '0', false, 0, null will all be converted to int 0 this way.

1, true and other numbers will keep their value however, I don't know if that's clear right away :)

Please review http://php.net/manual/en/language.types.type-juggling.php for more information.

Upvotes: 2

Robbert
Robbert

Reputation: 6582

You can check to see what the value of $sfideRicevute is and if it's null, display 0.

echo $sfideRicevute == null ? 0 : $sfideRicevute;

Upvotes: 1

Related Questions