PHP MySQL Select Where
The SELECT statement is used to fetch data from a database. The WHERE clause is used to filter data based on specific conditions. The WHERE clause can be
The SELECT statement is used to fetch data from a database. The WHERE clause is used to filter data based on specific conditions. The WHERE clause can be combined with the SELECT statement to fetch only specific data from the database.
Here is the basic syntax of the SELECT statement with WHERE clause:
PHP / SQL basic syntax of the SELECT statement with WHERE clause
SELECT column1, column2, ...
FROM table_name
WHERE condition;In the above syntax:
column1,column2, ... are the columns you want to fetch data from.table_nameis the name of the table you want to fetch data from.conditionis a logical expression that determines what data to retrieve.
Example
Consider a table named customers with the following data:
| id | name | country | |
|---|---|---|---|
| 1 | John | [email protected] | USA |
| 2 | Jane | [email protected] | UK |
| 3 | Alice | [email protected] | France |
Here is an example of how to use the SELECT statement with WHERE clause to retrieve only specific data from the customers table:
PHP / SQL example of how to use the SELECT statement with WHERE clause to retrieve only specific data from the customers table
SELECT name, email
FROM customers
WHERE country = 'USA';The above SELECT statement will return only the rows where the country column is equal to USA. The output will be:
name | email
----------|----------------------
John | [email protected]Multiple Conditions
You can also use multiple conditions in the WHERE clause. For example, you can retrieve all customers from the customers table who live in the USA and have an email address that ends with example.com.
PHP / SQL retrieve all customers from the customers table who live in the USA and have an email address that ends with example.com
SELECT name, email
FROM customers
WHERE country = 'USA'
AND email LIKE '%example.com';The above SELECT statement will return the following output:
name | email
----------|----------------------
John | [email protected]You can use logical operators such as AND and OR to combine multiple conditions in the WHERE clause.
Security Note: When filtering data with user-supplied input, always use prepared statements (e.g., PDO or MySQLi) to prevent SQL injection attacks.
Practice
What is the use of the WHERE clause in MySQL in PHP?