GURKE
GURKE

Reputation: 153

MYSQL Prepared Statements Select Row_Count

I have a simple SQL Query:

$stmt = $db_main->prepare("SELECT id FROM user WHERE username=? AND mail=? LIMIT 1");
$stmt->bind_param('ss', $username, $mail);
$stmt->execute();

And I want to know, if it found an user. So I want to count the rows found. I already tried to use rowCount (Not safe for SELECT) or num_rows or just looking if the result id is numeric (Which '' would not be, I hoped...)

There has to be an easy way to count the selected row, hasn't be?

Upvotes: 1

Views: 1008

Answers (1)

Trinimon
Trinimon

Reputation: 13967

Check number of rows returned with:

$stmt->num_rows;

Check for instance this site.

p.s.: added as per question in comment: use fetch() in order to get the next record.

...
$stmt->execute();
$stmt->bind_result($user_id); // access id
$stmt->store_result();        // optional: buffering (see below)

if ($data = $stmt->fetch()) {
    do {
        print("Id: " . $user_id); 

    } while ($data = $stmt->fetch());

} else {
    echo 'No records found.';
}

Regarding store_result() from the documentation: "You must call mysqli_stmt_store_result() for every query ..., if and only if you want to buffer the complete result set by the client ..."

Upvotes: 3

Related Questions