Skip to content Skip to sidebar Skip to footer

Count Number Of Mysql Rows

Im trying to count the number of rows in a MySQL database and report that number using PHP. I've read all the documentation and I think this piece of code should be working but no

Solution 1:

mysql_num_rows expects a query resource – you're supplying a string. You need to perform the query before you can expect to know anything about its result.

$sql = "SELECT * FROM messages WHERE recepiants='$username' AND readcheck='T'";
if(!$query = mysql_query($sql))
  trigger_error(mysql_error().' SQL: '.$sql);
$count = mysql_num_rows($query);

I suspect the above code will also generate an error based on your typo of 'recipients' in the query. Always check the return value of mysql_query.

Edit: As jeroen noted, if what you pasted is the entire code of that page then you have neglected to open a database connection. See mysql_connect and mysql_select_db.

Solution 2:

The thing you're missing is running the actual query:

<?php
session_start();
if ( isset($_SESSION['username']) ) {
    $username = $_SESSION['username'];
    $q = "SELECT * FROM messages WHERE recepiants='$username' AND readcheck='T'";
    $result = mysql_query($q);
    $count = mysql_num_rows($result);
?><divclass="user_info">Logged in as <?phpecho$username; ?> | <ahref="admin.php">Add a post</a> | <ahref="experiment.php">View Posts</a> | <ahref="inbox.php">Message Center <?phpecho$count; ?></a> | <ahref="logout.php">Log Out</a></div><?php } else {?>

Probably better would be to run a COUNT in the query, if that's all you need:

<?php
session_start();
if ( isset($_SESSION['username']) ) {
    $username = $_SESSION['username'];
    $q = "SELECT COUNT(*) AS Count FROM messages WHERE recepiants='$username' AND readcheck='T'";
    $result = mysql_query($q);
    $result = mysql_fetch_assoc($result)
    $count = $result['Count'];
?><divclass="user_info">Logged in as <?phpecho$username; ?> | <ahref="admin.php">Add a post</a> | <ahref="experiment.php">View Posts</a> | <ahref="inbox.php">Message Center <?phpecho$count; ?></a> | <ahref="logout.php">Log Out</a></div><?php } else {?>

And, as someone else noted, you need an active database connection.

http://www.php.net/manual/en/function.mysql-fetch-assoc.php

Solution 3:

You have not actually executed your query.

$q = "SELECT * FROM messages WHERE recepiants='$username' AND readcheck='T'";
$result = mysql_query($q);
if ($result) {
  $count = mysql_num_rows($result);
}

Solution 4:

This is wrong (there needs to be an actual query):

$q = "SELECT * FROM messages WHERE recepiants='$username' AND readcheck='T'";
$count = mysql_num_rows($q);

it should be:

$q = "SELECT * FROM messages WHERE recepiants='$username' AND readcheck='T'";
$result = mysql_query($q, $connection);
$count = mysql_num_rows($result);

Solution 5:

You are evaluating $q as a string, you're missing a mysql_query() on $q

Post a Comment for "Count Number Of Mysql Rows"