PHP & MySQL - Select Records Example


You can use the same SQL SELECT command into a PHP function mysql_query(). This function is used to execute the SQL command and then later another PHP function mysql_fetch_array() can be used to fetch all the selected data. This function returns the row as an associative array, a numeric array, or both. This function returns FALSE if there are no more rows.

The following program is a simple example which will show how to fetch / display records from the tutorials_tbl table.


The following code block will display all the records from the tutorials_tbl table.

Copy and paste the following example as mysql_example.php −

      <title>Selecting Records</title>
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $conn = mysqli_connect($dbhost, $dbuser, $dbpass);

         if(! $conn ) {
            die('Could not connect: ' . mysqli_error($conn));
         echo 'Connected successfully<br />';
         mysqli_select_db( $conn, 'TUTORIALS' );
         $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl";
         $retval = mysqli_query( $conn, $sql );
         if(! $retval ) {
            die('Could not get data: ' . mysqli_error($conn));
         while($row = mysqli_fetch_array($retval, MYSQL_ASSOC)) {
            echo "Tutorial ID :{$row['tutorial_id']}  ".
               "Title: {$row['tutorial_title']} ".
               "Author: {$row['tutorial_author']} ".
               "Submission Date : {$row['submission_date']} ".
         echo "Fetched data successfully\n";


Access the mysql_example.php deployed on apache web server, enter details and verify the output on submitting the form.

Entered data successfully

While doing a data insert, it is best to use the function get_magic_quotes_gpc() to check if the current configuration for magic quote is set or not. If this function returns false, then use the function addslashes() to add slashes before the quotes.

You can put many validations around to check if the entered data is correct or not and can take the appropriate action.