AdBlock Detected

We provide high-quality source code for free. Please consider disabling your AdBlocker to support our work.

Buy me a Coffee

Saved Tutorials

No saved posts yet.

Press Enter to see all results

How to Find the number of rows in the result set

By pushpam abhishek • •
Listen to this article

How to Find the number of rows in the result set

Before you can go through the data in your $resultSet variable, you must know how many database rows there are.

How to Find the number of rows in the result set


 <?php
 
 $numrows= mysql_num_rows ($resultSet );

?>

The method mysql_num_rows() returns the row count for a SELECT statement, whereas mysql_affected_rows() returns the number of rows affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

<?php
 
 $numrows= mysql_affected_rows ($conn );

?>

How To Retrieve the Data From the ResultSet

The MySQL extension has multiple methods to retrieve the data from a result set.

Fetch a single row from MySql


 <?php
 
 $sql = "SELECT * FROM user order by id desc limit 1";
 $resultSet = mysql_query($sql) or die(mysql_error());
 
 //Fetch a result row as an associative array, a numeric array, or both
 $row = mysql_fetch_array( $resultSet ); 

 OR

 //Get a result row as an enumerated array
 $row = mysql_fetch_row( $resultSet ); 

 OR

 //Fetch a result row as an associative array
 $row = mysql_fetch_assoc( $resultSet ); 

 OR

 //Fetch a result row as an object
 $row = mysql_fetch_object( $resultSet ); 


?>

Note: You can use any one method as per your need and get the data from $resultSet.

Fetch Multiple rows from MySql


 <?php
  $sql = "SELECT * FROM user order by id desc limit 20";
  $resultSet = mysql_query($sql) or die(mysql_error());

 //To print get all rows use followign code
 while($rows = mysql_fetch_array( $resultSet ))
 {
  Print "First Name: ".$rows['firstname'] . " ";
  Print "Last Name: ".$rows['lastname'] . " 
";
  Print "Phone Number: ".$rows['phone'] . " 
";
  Print "Address: ".$rows['address'] . " 
";
 }

?>

Clean-Up: Release the Resources

Once the required data has been retrieved from the result set, it is a recommended practice to free up the connection to the database server so that further queries can be executed.

 <?php
 
  mysql_free_result($resultSet);
 
?>


Close Mysql Connection

The method mysql_close() closes the non-persistent connection to the MySQL server that is associated with the specified database connection handle. If the connection handle is not specified, by default, the last connection opened by mysql_connect() is assumed.

The following statement in the sample PHP script closes the database connection.
 <?php
 mysql_close($conn);
?>

Read More


Share this post

pushpam abhishek

About pushpam abhishek

Pushpam Abhishek is a Software & web developer and designer who specializes in back-end as well as front-end development. If you'd like to connect with him, follow him on Twitter as @pushpambhshk

Comments