1

I have the following PHP code:

$sql   = new mysqli(/*connection info/db*/);
$query = $sql->$query("SELECT * from users WHERE /* rest of code */);

I was now wondering if there was any way I could retrieve the amount of rows that the above query found...

1

3 Answers 3

2

You should consider using PDO, it's safer and a more object oriented approach:

$database = new PDO(/*connection info/db*/);

$statement = $database->prepare('SELECT FROM fruit WHERE fruit_id = ? AND name = ?');
$statement->bindValue( 1, 'fruit_id_value' );
$statement->bindValue( 2, 'Banana' );
$statement->execute();

$count = $statement->rowCount(); # <-- The row count you are looking for!

--> visit http://php.net/manual/en/pdostatement.rowcount.php for more info

Sign up to request clarification or add additional context in comments.

Comments

0

in Mysqli I know you can do

printf("Number of rows: %d.\n", $sql->num_rows);

Here is all the code

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
if ($stmt = $mysqli->prepare($query)) {

    /* execute query */
    $stmt->execute();

    /* store result */
    $stmt->store_result();

    printf("Number of rows: %d.\n", $stmt->num_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();
?>

I got that from this php manual http://php.net/manual/en/mysqli-stmt.num-rows.php

Comments

0

There is a modifier for the SELECT query that holds on to the information of the count you need: SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS  * from users WHERE /* rest of code */

After running that query, you can run SELECT FOUND_ROWS(); to get the resulting number of rows.

If all you need is the count, you can just do

SELECT count(*) from users WHERE /* rest of code */

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.