PHP MySQL tutorial

Selecting MySQL Table Data via PHP Script

The last article explained the process of inserting data into a table in MySQL database. This article throws light on selecting data from a table in MySQL. It is extremely simple and straight forward process. To do so, a SELECT query is used in MySQL. The syntax of the SELECT query is as follows.

SELECT column1, column2, column3 FROM table

The above code will fetch all values for column1, column2 and column3 for all the records in the table. You can also retrieve values from all the columns of the table via following syntax.

SELECT * FROM table

Selecting MySQL table data via Object Oriented MySQLi

To select a table data via MySQLi, pass the query for selecting data to the query function of the mysqli object. The following example demonstrates this concept.




Using MySQLi for Selecting data



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Select table data

$query = "SELECT patient_fname, patient_age FROM Patient";
$output = $connection->query($query);

if ($output->num_rows > 0) {
    // output data of each row
    while($row = $output->fetch_assoc()) {
        echo "First Name: " . $row["patient_fname"]. " - Age: " . $row["patient_age"]."
"; } } else { echo "0 results"; } $connection->close(); ?>

Download the code

The above code will retrieve values for patient_fname and patient_age columns of Patient table of the Hospital database.

Select Table data via Procedural MySQLi

Selecting table data via procedural MySQLi is very simple. Just replace mysqli object with mysqli_connect function. The following example demonstrates this concept.




Using MySQLi for Selecting Data



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Select table data

$query = "SELECT patient_fname, patient_age FROM Patient";
$output = $connection->query($query);

if ($output->num_rows > 0) {
    // output data of each row
    while($row = $output->fetch_assoc()) {
        echo "First Name: " . $row["patient_fname"]. " - Age: " . $row["patient_age"]."
"; } } else { echo "0 results"; } $connection->close(); ?>

Download the code

<<< Inserting Data in MySQL Table via PHP ScriptWhere Clause in MySQL >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .