Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking result before using $stmt -> fetch() [duplicate]

Tags:

php

mysql

mysqli

probably a stupid question. I have the following code:

while ($stmt -> fetch()) {
    echo "<p><strong>" .$name. "</strong><br />" .$comment. "</p>";
}

I would like to execute the while ONLY if $stmt -> fetch() returns at least one row (this is a SELECT query).. but if I do

if ($stmt -> fetch())

It gets executed already one time, and I want to avoid this. Any clue?

Thanks in advance.

like image 813
wiredmark Avatar asked May 26 '26 07:05

wiredmark


2 Answers

http://php.net/manual/en/mysqli-stmt.num-rows.php

Try using $stmt->num_rows > 0

$stmt->store_result();
if( $stmt->num_rows > 0 )
{
    while( $stmt->fetch() ) {
        echo "<p><strong>" .$name. "</strong><br />" .$comment. "</p>";
    }
}

why mysqli_result has a fetchAll function and mysqli_stmt doesnt.... i have no idea.


Longer, but may work

$result = $stmt->fetch();
if( !empty( $result )
{
    do
    {
        echo "<p><strong>" .$name. "</strong><br />" .$comment. "</p>";
    } while( $result = $stmt->fetch() ); 
}
like image 54
Ascherer Avatar answered May 27 '26 21:05

Ascherer


I think you have to query th db at-least one time to get count.

like image 38
Tanmay Majumder Avatar answered May 27 '26 22:05

Tanmay Majumder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!