PHP MySQL tutorial

Select Unique Data via Distinct In MySQL

Multiple records in MySQL table can have same value for different columns. For instance, many patients can have same first name and same age. What if you only want to select unique first names of the patient where patient’s first name doesnt report or you might want to see what are the different ages of the patient without repeating values for the age twice. The DISTINCT operator in MySQL allows to select unique column values. Syntax of DISTINCT operator is as follows:

SELECT DISTINCT column1, column2, column3 FROM table

Selecting unique MySQL table data via Object Oriented MySQLi

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




Using MySQLi for Unique Data Selection



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

$query = "SELECT DISTINCT patient_fname 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"]."
"; } } else { echo "0 results"; } $connection->close(); ?>

Download the code

The above code will retrieve unique values for patient_fname column of Patient table of the Hospital database.

Select Unique Table data via Procedural MySQLi

Selecting unique table data via procedural MySQLi is very simple. Just replace mysqli object with mysqli_connect function. Have a look at the following example.




Using MySQLi for Unique Data Selection



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

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

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

Download the code

The above code will retrieve unique values for patient_age column of Patient table of the Hospital database.

<<< LIKE Query in MySQLIN Operator in MySQL >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .