PHPSuperBlog.com

Check how many record in the MySQL database matches the query

Editor’s note: In some cases, you might like to check how many records in the MySQL database which matches the query you entered. Case such as a login system where you want to check if there is a record matches the user name and the password inputted , here is an example

I have created a table in the MySQL database called “test” and with a field called “name” with 3 records “john”, “peter” and “peter”. I put 2 “peter” into the table intentionally because i want to show that when a query is called to check the number of row containing “peter”, it will show up “2″ on the screen.

I have created a php file with the following codes:

First we have to connect to the database:

mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");

Then we create a query to select all records with “peter” in it from the table “test”:

$query = "SELECT * FROM test where name = 'peter'";

We then run the query and store the result in a variable:

$result = mysql_query($query);

Now we use the mysql_num_rows() function to check how many rows in the MySQL database matches the query and the result is stored in a PHP variable $count:

$count=mysql_num_rows($result);

At last we print out the result onto the screen to see if the whole thing works correctly:

echo $count;

Altogether we have:

<?php
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed");
mysql_select_db("DataBase Name")or die("Connection Failed");
$query = "SELECT * FROM test where name = 'peter'";
$result = mysql_query($query);
$count=mysql_num_rows($result);
echo $count;
?>

We get “2″ in this case because there are 2 records in the MySQL database with “peter” in the “name” field.

VN:F [1.9.3_1094]
Rating: 10.0/10 (2 votes cast)
VN:F [1.9.3_1094]
Rating: +1 (from 1 vote)
Check how many record in the MySQL database matches the query, 10.0 out of 10 based on 2 ratings

Similar Posts:

Leave a comment