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<?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<?php
  $query = "SELECT * FROM users WHERE id=2";
?>

Example

Let's select users with an id greater than 2:

php<?php
  $query = "SELECT * FROM users WHERE id>2";
?>

Example

Let's select users with an id greater than or equal to 2:

php<?php
  $query = "SELECT * FROM users WHERE id>=2";
?>

Example

Let's select users with an id not equal to 2:

php<?php
  $query = "SELECT * FROM users WHERE id!=2";
?>

Example

Instead of the != command, you can use the <> command:

php<?php
  $query = "SELECT * FROM users WHERE id<>2";
?>

Example

Let's select users aged 23 years:

php<?php
  $query = "SELECT * FROM users WHERE age=23";
?>

Example

Let's select users with a salary of 500:

php<?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<?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<?php
  $query = "SELECT * FROM users";
?>

Practical Tasks

Задание 1

Select a user with an id equal to 3.

Задание 2

Select users with a salary of 900.

Задание 3

Select users aged 23 years.

Задание 4

Select users with a salary greater than 400.

Задание 5

Select users with a salary equal to or greater than 500.

Задание 6

Select users with a salary NOT equal to 500.

Задание 7

Select users with a salary equal to or less than 500.