Using WHERE to limit data in MySql and PHP
You can add a WHERE part to your SQL. But before you do, make sure you read the security section.
Using WHERE limits the records returned from a SQL statement. Most of the time, you don’t want to return all the records from your table. Especially if you have a large number of records. This will just slow things down unnecessarily. Instead, use WHERE. In the SQL below, we’re using WHERE to bring back only the matching records from the AddressBook table:
$SQL = "SELECT * FROM AddressBook WHERE email = '[email protected]' ";
When the following code is run, only the records that have an email field of [email protected] will be returned.
You can specify more fields in your WHERE clause:
$SQL = "SELECT * FROM AddressBook WHERE First_Name = 'Bill' AND Surname = 'Gates'";
In the SQL statement above, we’ve used the AND operator as well. Only records that have First_Name value of Bill AND a Surname value of Gates will be returned.
You can also use the operators you saw in the variables section:
$SQL = "SELECT * FROM AddressBook WHERE ID >= '10' ";
In this SQL statement, we’re specifying that all the records from the AddressBook table should be returned WHERE the ID column is greater than or equal to 10.
Getting the hang of WHERE can really speed up your database access, and is well worth the effort. An awareness of the security issues involved is also a must.