Check how many record in the MySQL database matches the query
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.
Similar Posts:
- Copy one table’s field records into another table’s field in MySQL database with PHP
- Display data from MySQL with PHP
- Merging 2 MySQL tables with PHP – update one table’s field with another table’s field data (both table have one common field)
- Get MySQL database records as HTML form text field’s value
- Find the number of column (field) of a table in MySQL database






