PHP MySQL WHERE Clause
In this tutorial you will learn how to select the records from a MySQL database table based on specific conditions using PHP.
Filtering the Records
The WHERE
clause is used to extract only those records that fulfill a specified condition.
The basic syntax of the WHERE
clause can be given with:
Let's make a SQL query using the WHERE
clause in SELECT
statement, after that we'll execute this query through passing it to the PHP mysqli_query()
function to get the filtered data.
Consider we've a persons table inside the demo database that has following records:
+----+------------+-----------+----------------------+ | id | first_name | last_name | email | +----+------------+-----------+----------------------+ | 1 | Peter | Parker | [email protected] | | 2 | John | Rambo | [email protected] | | 3 | Clark | Kent | [email protected] | | 4 | John | Carter | [email protected] | | 5 | Harry | Potter | [email protected] | +----+------------+-----------+----------------------+
The following PHP code selects all the rows from the persons table where first_name='john':
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM persons WHERE first_name='john'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
After filtration the result set will look something like this:
+----+------------+-----------+---------------------+ | id | first_name | last_name | email | +----+------------+-----------+---------------------+ | 2 | John | Rambo | [email protected] | | 4 | John | Carter | [email protected] | +----+------------+-----------+---------------------+