rowCount does not return zero

Asked

Viewed 89 times

0

I have this script:

<?php
include 'config.php';
if(isset($_POST)){
$user = isset($_POST['user']) ? strip_tags($_POST['user']) : 'HabboColorFS';
$rank = $pdo->query("SELECT * FROM topicos_comentarios WHERE autor='".$user."'")->rowCount();
$usuario = $pdo->prepare("SELECT * FROM usuarios WHERE usuario='".$user."'");
$usuario->execute();
    while($ver = $usuario->fetch(PDO::FETCH_ASSOC)){
?>
<?php print $usuario->rowCount(); ?>
<div class="image" style="background-image: url('<?php echo $cx_uploads; ?>/<?php echo $ver['avatar']; ?>')">
<div class="comments"><i class="fa fa-comments" aria-hidden="true"></i>&nbsp;<?php echo $rank; ?></div>
<div class="comments"><i class="fa fa-commenting" aria-hidden="true"></i>&nbsp;123</div>
<div class="base">
    <div class="avatar" style="background-image: url('https://www.habbo.com.br/habbo-imaging/avatarimage?&user=<?php echo $ver['usuario']; ?>&action=std&direction=3&head_direction=3&img_format=png&gesture=std&headonly=0&size=s')"></div>
</div>
</div>
<div class="type day">
<div class="totype"><i class="fa fa-trophy" aria-hidden="true">
</i>&nbsp;&nbsp;RANKING DO DIA</div>
<div class="position">178º</div>
</div>
<div class="type all">
<div class="totype"><i class="fa fa-trophy" aria-hidden="true">
</i>&nbsp;&nbsp;RANKING GERAL</div>
<div class="position">178º</div>
</div>
<?php } } ?>

I am trying to make an if that when $user->rowCount() is 0 it display an error message "echo "no user found"".

I put print $usuario->rowCount(); and I tried with echo tbm, I already did if that way, but when I do a purposeful search to empty it does not display 0.

How can I solve?

  • 1

    Have you tried putting the rowCount outside the while in which you do the fetch?

  • Wow, it worked out! kkkk. Thanks, can you explain to me why it only works out?

  • Why the method fetch will return false when there are no records, in which case the while.

  • Understood! Thank you very much.

1 answer

1


It will not be displayed on the screen that there are zeros records in the database because the display statement of this value:

print $usuario->rowCount();

It’s inside a loop:

while($ver = $usuario->fetch(PDO::FETCH_ASSOC)) {...}

Looking at the documentation of the method fetch, there is the following return description:

The Return value of this Function on Success depends on the fetch type. In all cases, FALSE is returned on Failure.

The returned value will depend on the parameter set, in case of success, or FALSE in any other case. If the number of records is null, the method will return false and therefore the loop will not run. If you really want to display the amount of records, even if it is zero, just put the print out of the loop:

print $usuario->rowCount();

while($ver = $usuario->fetch(PDO::FETCH_ASSOC)) {
    ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.