amadeo
amadeo

Reputation: 109

Number of rows in a MySQL table?

Can anyone tell me what I am doing wrong here? This code doesn't echo out anything. I would like to see the number of rows containing $tag in the urlslug field.

<?php

$query = mysqli_query($mysqli, "SELECT * FROM tags WHERE urlslug='$tag'");
$num_rows = mysql_num_rows($query);
echo $num_rows;

Thanks! :)

Upvotes: 0

Views: 100

Answers (6)

user2161895
user2161895

Reputation:

my ans with @Sverri M. Olsen's ans Number of rows in a MySQL table?:

When you COUNT(*) it takes in count column indexes, so it will be the best result. Mysql with MyISAM engine actually stores row count, it doensn't count all rows each time you try to count all rows. (based on primary key's column)

If the COUNT(*) is slow, you should run EXPLAIN on the query, and check if indexes are really used, and where should they be added.

and +1 for @Sverri M. Olsen

Upvotes: 0

Michael Kunst
Michael Kunst

Reputation: 2988

You're using mysqli_query function, but then you have the deprecated mysql_num_rows function. Try mysqli_num_rows instead.

Upvotes: 5

Sverri M. Olsen
Sverri M. Olsen

Reputation: 13263

It is not very efficient to select everything in a table, count it, and then throw it away again. You should use the MySQL COUNT function to count the rows:

$result = mysqli_query($mysqli, "SELECT COUNT(*) as numRows FROM tags WHERE urlslug='$tag'");
$data = mysqli_fetch_array($result);
var_dump($data);

Upvotes: 2

Mahendra Jella
Mahendra Jella

Reputation: 5596

Try this

<?php

$query = mysqli_query($mysqli, "SELECT * FROM tags WHERE urlslug='$tag'");
$num_rows = mysqli_num_rows($mysqli,$query);
echo $num_rows;

?>

Upvotes: 0

AVM
AVM

Reputation: 592

try this

mysqli_num_rows($query)

Upvotes: 1

Vishal Sharma
Vishal Sharma

Reputation: 1372

try this

$query = mysqli_query($mysqli, "SELECT * FROM tags WHERE urlslug='".$tag."'");
$num_rows = mysqli_num_rows($query);
echo $num_rows;

Upvotes: -2

Related Questions