Selecting Records with SQL Query to Database in PHP
In the test code, you have already seen the SELECT command,
which selects data from the database. Let's
now take a closer look at its syntax.
Here it is:
<?php
$query = "SELECT * FROM table WHERE condition";
?>
As you can see, after the table name, you can
also add the WHERE command, where you can
write constraints on the selected records.
The following comparison operations are allowed in the condition:
=, !=, <>, <,
>, <=, >=.
Let's look at their application with examples.
Example
Let's select a user with an id equal to 2:
<?php
$query = "SELECT * FROM users WHERE id=2";
?>
Example
Let's select users with an id greater than 2:
<?php
$query = "SELECT * FROM users WHERE id>2";
?>
Example
Let's select users with an id greater than or equal to
2:
<?php
$query = "SELECT * FROM users WHERE id>=2";
?>
Example
Let's select users with an id not equal to 2:
<?php
$query = "SELECT * FROM users WHERE id!=2";
?>
Example
Instead of the != command, you can use the
<> command:
<?php
$query = "SELECT * FROM users WHERE id<>2";
?>
Example
Let's select users aged 23 years:
<?php
$query = "SELECT * FROM users WHERE age=23";
?>
Example
Let's select users with a salary of 500:
<?php
$query = "SELECT * FROM users WHERE salary=500";
?>
Example
Let's select a user with the name 'user1'. Here
an important nuance awaits us: since the name is a
string, it must be enclosed in quotes:
<?php
$query = "SELECT * FROM users WHERE name='user1'";
?>
Example
If the WHERE command is absent, then
all records from the table will be selected. Let's
select all employees:
<?php
$query = "SELECT * FROM users";
?>
Practical Tasks
Select a user with an id equal to 3.
Select users with a salary of 900.
Select users aged 23 years.
Select users with a salary greater than 400.
Select users with a salary equal to or greater than
500.
Select users with a salary NOT equal to 500.
Select users with a salary equal to or less than
500.