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. It 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 Adglob_tbl table.

Example

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

Copy and paste the following example as mysql_example.php −

<html>
   <head>
      <title>Selecting Records</title>
   </head>
   <body>
      <?php
         $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, 'ADGLOB' );
         $sql = "SELECT adglob_id, adglob_title, adglob_author, submission_date FROM adglob_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 "Adglob ID :{$row['adglob_id']}  ".
               "Title: {$row['adglob_title']} ".
               "Author: {$row['adglob_author']} ".
               "Submission Date : {$row['submission_date']} ".
               "--------------------------------";
         } 
         echo "Fetched data successfully\n";
         mysqli_close($conn);
      ?>
   </body>
</html>

Output

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.

This Post Has One Comment

Leave a Reply