Pages Menu
TwitterRssFacebook
Categories Menu

Posted by in PHP Tutorials and Resources | 0 Comments

PHP: Check If MySql Query is Successful

Checking of a mysql query for success or not is very easy by using PHP. Simply you can count the resulting rows extracted by a mysql query. We will use PHP mysql_num_rows function to get number rows in the result of a query execution. Below is the method, if mysql query is successful or not:

 

You might find these useful

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$con = mysql_connect("localhost", "username_of_mysql_client", "mysql_password");
//Now select the database
mysql_select_db("db_name", $con);

$thequery = mysql_query("SELECT * from `your_table`, $con);
//Apply condition to filter out whether the query returns results or not
//Query will result '0' if nothing found, else it will return results 1 to rows_numbers

if(mysql_num_rows($thequery) > 0) {
//Query is successful, do something
echo "do something";
}
else {
//Query didn't return anything
echo "do something else";
}

But after the release of PHP 5.5.0, mysql_num_rows() function is deprecated and will be removed in the future versions of PHP. So I will recommend not to use mysql_num_rows() anymore.

Alternative

According to the new PHP version, you should use mysqli_stmt_num_rows() function. It works like mysql_num_rows() but has better security. The code will be look like below after using mysqli_stmt_num_rows():

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
$con = mysqli_connect("localhost", "username_of_mysql_client", "mysql_password", "db_name");

$thequery = mysqli_prepare($con, "SELECT * from `your_table`);

if(mysqli_stmt_num_rows($thequery) > 0) {
//Query is successful, do something
echo "do something";
}
else {
//Query didn't return anything
echo "do something else";
}

Post a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>