PHP MySQL Where Clause

To select data that matches a specified condition, add a WHERE clause to the SELECT statement.

WHERE clause

To select data that matches a specified condition, add a WHERE clause to the SELECT statement.

Syntax

SELECT column FROM table
WHERE column operator value

The following operators can be used with the WHERE clause:

Operators Description
= Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
BETWEEN Between a range containing
LIKE Search for matching patterns

Note:SQL statements are case-insensitive. WHERE is equivalent to where.

To make PHP execute the above statement, we must use the mysql_query() function. This function is used to send queries and commands to the SQL connection.

Example

The following example selects all rows from the "Persons" table where FirstName='Peter':

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons
WHERE FirstName='Peter'");
while($row = mysql_fetch_array($result))
  {
  echo $row['FirstName'] . " " . $row['LastName'];
  echo "<br />";
  }
?>

The output of the above code is:

Peter Griffin