How to Select Data Into MySQL Database Using PHP ?

Select :

Select Data From a MySQL Database

The SELECT statement is used to select data from one or more tables

The SQL SELECT command is used to fetch data from the MySQL database. You can use this command at mysql> prompt as well as in any script like PHP.

Syntax :

  • Columns are the column names to be selected :

SELECT column1,column2,.,column n from table_name;

  • You want to display all the columns, you can use * instead of column names :

SELECT * FROM table name ;

PHP mysql_query() function is used to execute select query. Since PHP 5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_query()
  • PDO::__query()

Implementation of the Select Query :
Let us consider the following table ‘ Data ‘ with three columns ‘ FirstName ‘, ‘ LastName ‘ and ‘ Age ‘.

 First nameLast nameAge
Rajkumar20
Rohankumar22
Sitakumari23
priyakumari20

To select all the data stored in the ‘ Data ‘ table, we will use the code mentioned below.

SELECT Query using Procedural Method :

<?php 
$link = mysqli_connect(“localhost”, “root”, “”, “company”);  
  if ($link === false) {
    die(“ERROR: Could not connect. ”
                  .mysqli_connect_error());
}
   $sql = “SELECT * FROM Data”;
if ($res = mysqli_query ($link, $sql)) {
    if (mysqli_num_rows ($res) > 0) {  
       echo “<table>”;  
       echo “<tr>”;  
       echo “<th>Firstname</th>”;  
       echo “<th>Lastname</th>”;  
       echo “<th>age</th>”;   
      echo “</tr>”;  
       while ($row = mysqli_fetch_array($res) ) {
            echo “<tr>”;  
           echo “<td>”.$row[‘Firstname’].”</td>”;
            echo “<td>”.$row[‘Lastname’].”</td>”;  
           echo “<td>”.$row[‘Age’].”</td>”;  
           echo “</tr>”;   
      }     
    echo “</table>”;
        mysqli_free_result ($res);
    }   
  else
{      
   echo “No matching records are found.”;     }
} else
{
echo “ERROR: Could not able to execute $sql. ”                                 
mysqli_close($link);
}
mysqli_error($link);
?>
 First nameLast nameAge
Rajkumar20
Rohankuamr22
Sitakumari23
priyakumari20

Leave a Reply