MYSQLi SELECT

Read data from a MySQL database

We learned to add data to the database. In this section, how do we read the data from the database and display it on the page?

Query data with select


Category     Detailed explanation
Basic grammarSelect * from table;
Instance Select * from MyGuests;
 Example descriptionQuery all results in all fields in the MyGuests table
Note : " * " is a regular expression that means matching all
 
Instance

We query the data we added to the MyGuests table and display it on the page.

 Header("Content-type:text/html;charset=utf-8"); //Set the encoding
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";
 
 // Create a connection
 $conn = new mysqli($servername, $username, $password, $dbname);
 / / Check the connection
 If ($conn->connect_error) {
     Die("Connection failed: " . $conn->connect_error);
 }
 
 $sql = "SELECT * FROM MyGuests";
 $result = $conn->query($sql);
 
 If ($result->num_rows > 0) {
     / / Output each line of data
     While($row = $result->fetch_assoc()) {
         Echo "id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] ." ".$row['email'] . "
";
     }
 } else {
     Echo "0 results";
 }
 $conn->close();


See if it is the data in our MyGuests table.

But if we just want to query two of the fields, such as firstname and email, see the example below.

 Header("Content-type:text/html;charset=utf-8"); //Set the encoding
 $servername = "localhost";
 $username = "root";
 $password = "root";
 $dbname = "test";
 
 // Create a connection
 $conn = new mysqli($servername, $username, $password, $dbname);
 / / Check the connection
 If ($conn->connect_error) {
     Die("Connection failed: " . $conn->connect_error);
 }
 
 $sql = "SELECT firstname, email FROM MyGuests";
 $result = $conn->query($sql);
 
 If ($result->num_rows > 0) {
     / / Output each line of data
     While($row = $result->fetch_assoc()) {
         Echo " - Name: ". $row["firstname"]. "--------".$row['email'] ."
";
     }
 } else {
     Echo "0 results";
 }
 $conn->close();
 
Just replace * with a specific field:


Last Updated: 2018-07-06 12:32:44 By akshay

SHARE THIS

share_facebook share_twitter share_google_plus

Please Comment Here :