PHP MySQL tutorial

Where Clause in MySQL

In the last article, we saw how we can select data from a table via SELECT statement. SELECT statement alone retrieves all the record from a table, however we seldom need all the records from the table. Most of the time we need filtered records. For instance, we might want to retrieve records of only those patients with age greater than 25. In such cases WHERE statement is used. The syntax of WHERE statement is as follows.

SELECT column1, column2, column3 FROM table
WHERE condition1 AND/OR condition2 .... AND/OR conditionN

In the above code, the condition1, condition2 etc are the conditions that are imposed while selecting table data.

WHERE clause in Object Oriented MySQLi

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




Using WHERE clause in MySQLi



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Implementing WHERE clause

$query = "SELECT patient_fname, patient_age FROM Patient ".
    "WHERE patient_age > 25";
$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 where patient_age column has a value greater than 25.

Select Table data via Procedural MySQLi

Selecting filtered table data using WHERE clause in MySQLi is very simple. Just replace mysqli object with mysqli_connect function. The following example demonstrates this concept.




Using WHERE clause in MySQLi



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Implementing WHERE clause

$query = "SELECT patient_fname, patient_age FROM Patient ".
    "WHERE patient_age > 25";
$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

<<< Selecting MySQL Table Data via PHP ScriptUpdate MySQL Table data via PHP Script >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .