Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

PHP MySQL Where clause


May 11, 2021 PHP


Table of contents


PHP MySQL Where clause

From the contents of the last section, you can already get data from the data table using MySQL's SELECT command, and in this section we can use the WHERE command to filter out the results that meet the criteria.

The WHERE clause is used to filter records.


Where clause

The WHERE clause is used to extract records that meet the specified criteria.

Grammar

SELECT column_name(s)
FROM table_name
WHERE column_name operator value

To learn more about SQL, visit our SQL tutorial.

In order for PHP to execute the statement above, we must use mysqli_query () function. This function is used to send queries or commands to MySQL connections.

Instance

The following example picks all the firstName's 'Peter's' rows from the "Peoples" table:

<?php
 $con=mysqli_connect("example.com","peter","abc123","my_db");
 // Check connection
 if (mysqli_connect_errno())
 {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $result = mysqli_query($con,"SELECT * FROM Persons
 WHERE FirstName='Peter'");

 while($row = mysqli_fetch_array($result))
 {
 echo $row['FirstName'] . " " . $row['LastName'];
 echo "<br>";
 }
 ?>

The above code will output:

Peter Griffin

In the next section, we'll show you how to sort filtered records.