PHP MySQL tutorial

AND/OR Operators In MySQL

In some of the previous articles, we studied how to filter data via, WHERE, IN and BETWEEN clauses. We can also set multiple conditions for filtering table data. For this purpose AND and OR operators are used MySQL. The AND operators works as logical AND and the OR operator works as the logical OR. The syntax for AND and OR operator is as follows:

SELECT column1, column2, column3 
FROM table
WHERE column1= value1 AND column2 IN (value1, value2, value3 ....)

Using AND/OR Operator in Object Oriented MySQLi

To join multiple WHERE clauses using AND/IN operator via MySQLi, pass the query for selecting filtered data to the query function of the mysqli object. The following example demonstrates this concept.




Using AND Operator in Object Oriented Mysqli



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Using AND Operator

$query = "SELECT patient_fname, patient_age ".
"FROM Patient ".
"WHERE patient_age BETWEEN 30 and 50 AND patient_fname LIKE '%x'";
$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 column of all the patients whose age is between 30 and 50 and whose patient_fname column has value that ends with ‘x’.

Using AND/OR Operator in procedural MySQLi

Selecting filtered table data via AND/OR operator in procedural MySQLi is very simple. Just replace mysqli object with mysqli_connect function. Have a look at the following example.




Using AND Operator in Mysqli



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Using AND Operator

$query = "SELECT patient_fname, patient_age ".
"FROM Patient ".
"WHERE patient_age BETWEEN 40 and 50 OR patient_fname LIKE '%n'";
$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 column of all the patients whose age is between 40 and 50 or whose patient_fname column has value that ends with ‘n’.

<<< Using BETWEEN operator in MySQLSelecting Limited records via LIMIT in MySQL >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .