Sql запросы where php

PHP MySQL WHERE Clause

In this tutorial you will learn how to select the records from a MySQL database table based on specific conditions using PHP.

Filtering the Records

The WHERE clause is used to extract only those records that fulfill a specified condition.

The basic syntax of the WHERE clause can be given with:

Let’s make a SQL query using the WHERE clause in SELECT statement, after that we’ll execute this query through passing it to the PHP mysqli_query() function to get the filtered data.

Consider we’ve a persons table inside the demo database that has following records:

+----+------------+-----------+----------------------+ | id | first_name | last_name | email | +----+------------+-----------+----------------------+ | 1 | Peter | Parker | peterparker@mail.com | | 2 | John | Rambo | johnrambo@mail.com | | 3 | Clark | Kent | clarkkent@mail.com | | 4 | John | Carter | johncarter@mail.com | | 5 | Harry | Potter | harrypotter@mail.com | +----+------------+-----------+----------------------+

The following PHP code selects all the rows from the persons table where first_name=’john’:

Example

 // Attempt select query execution $sql = "SELECT * FROM persons WHERE first_name='john'"; if($result = mysqli_query($link, $sql)) < if(mysqli_num_rows($result) >0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = mysqli_fetch_array($result))< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Close result set mysqli_free_result($result); > else < echo "No records matching your query were found."; >> else < echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); >// Close connection mysqli_close($link); ?>
connect_error); > // Attempt select query execution $sql = "SELECT * FROM persons WHERE first_name='john'"; if($result = $mysqli->query($sql))< if($result->num_rows > 0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = $result->fetch_array())< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Free result set $result->free(); > else < echo "No records matching your query were found."; >> else< echo "ERROR: Could not able to execute $sql. " . $mysqli->error; > // Close connection $mysqli->close(); ?>
setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); > catch(PDOException $e)< die("ERROR: Could not connect. " . $e->getMessage()); > // Attempt select query execution try< $sql = "SELECT * FROM persons WHERE first_name='john'"; $result = $pdo->query($sql); if($result->rowCount() > 0)< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; while($row = $result->fetch())< echo ""; echo ""; echo ""; echo ""; echo ""; echo ""; > echo "
idfirst_namelast_nameemail
" . $row['id'] . "" . $row['first_name'] . "" . $row['last_name'] . "" . $row['email'] . "
"; // Free result set unset($result); > else < echo "No records matching your query were found."; >> catch(PDOException $e)< die("ERROR: Could not able to execute $sql. " . $e->getMessage()); > // Close connection unset($pdo); ?>

After filtration the result set will look something like this:

+----+------------+-----------+---------------------+ | id | first_name | last_name | email | +----+------------+-----------+---------------------+ | 2 | John | Rambo | johnrambo@mail.com | | 4 | John | Carter | johncarter@mail.com | +----+------------+-----------+---------------------+

Источник

Читайте также:  Code check all php

PHP MySQL Use The WHERE Clause

The WHERE clause is used to extract only those records that fulfill a specified condition.

To learn more about SQL, please visit our SQL tutorial.

Select and Filter Data With MySQLi

The following example selects the id, firstname and lastname columns from the MyGuests table where the lastname is «Doe», and displays it on the page:

Example (MySQLi Object-oriented)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>

$sql = «SELECT id, firstname, lastname FROM MyGuests WHERE lastname=’Doe'»;
$result = $conn->query($sql);

if ($result->num_rows > 0) // output data of each row
while($row = $result->fetch_assoc()) echo «id: » . $row[«id»]. » — Name: » . $row[«firstname»]. » » . $row[«lastname»]. «
«;
>
> else echo «0 results»;
>
$conn->close();
?>

Code lines to explain from the example above:

First, we set up the SQL query that selects the id, firstname and lastname columns from the MyGuests table where the lastname is «Doe». The next line of code runs the query and puts the resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an associative array that we can loop through. The while() loop loops through the result set and outputs the data from the id, firstname and lastname columns.

The following example shows the same as the example above, in the MySQLi procedural way:

Example (MySQLi Procedural)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) die(«Connection failed: » . mysqli_connect_error());
>

$sql = «SELECT id, firstname, lastname FROM MyGuests WHERE lastname=’Doe'»;
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) // output data of each row
while($row = mysqli_fetch_assoc($result)) echo «id: » . $row[«id»]. » — Name: » . $row[«firstname»]. » » . $row[«lastname»]. «
«;
>
> else echo «0 results»;
>

You can also put the result in an HTML table:

Example (MySQLi Object-oriented)

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDB»;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) die(«Connection failed: » . $conn->connect_error);
>

$sql = «SELECT id, firstname, lastname FROM MyGuests WHERE lastname=’Doe'»;
$result = $conn->query($sql);

if ($result->num_rows > 0) echo «

«;
// output data of each row
while($row = $result->fetch_assoc()) echo «

«;
>
echo «

ID Name
«.$row[«id»].» «.$row[«firstname»].» «.$row[«lastname»].»

«;
> else echo «0 results»;
>
$conn->close();
?>

Select Data With PDO (+ Prepared Statements)

The following example uses prepared statements.

It selects the id, firstname and lastname columns from the MyGuests table where the lastname is «Doe», and displays it in an HTML table:

Example (PDO)

class TableRows extends RecursiveIteratorIterator <
function __construct($it) <
parent::__construct($it, self::LEAVES_ONLY);
>

function current() return «

» . parent::current(). «

«;
>

$servername = «localhost»;
$username = «username»;
$password = «password»;
$dbname = «myDBPDO»;

try $conn = new PDO(«mysql:host=$servername;dbname=$dbname», $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare(«SELECT id, firstname, lastname FROM MyGuests WHERE lastname=’Doe'»);
$stmt->execute();

Источник

Выборка записей при SQL запросе к базе в PHP

В тестовом коде вы уже видели команду SELECT , выполняющую выборку данных из БД. Давайте теперь подробнее разберемся с ее синтаксисом. Вот он:

Как вы видите, после имени таблицы можно еще дописать команду WHERE, в которой можно писать ограничение на выбираемые записи. В условии допустимы следующие операции сравнения: = , != , <> , , > , , >= .

Давайте посмотрим их применение на примерах.

Пример

Выберем юзера с id , равным 2 :

Пример

Выберем юзеров с id , большим 2 :

Пример

Выберем юзеров с id , большим или равным 2 :

Пример

Выберем юзеров с id , не равным 2 :

Пример

Вместо команды != можно писать команду <> :

Пример

Выберем юзеров возрастом 23 года:

Пример

Выберем юзеров с зарплатой 500 :

Пример

Выберем юзера с именем ‘user1’ . Здесь нас поджидает важный нюанс: так как имя является строкой, то его необходимо взять в кавычки:

Пример

Если команда WHERE отсутствует, то выберутся все записи из таблицы. Давайте выберем всех работников:

Практические задачи

Выберите юзера с id , равным 3 .

Выберите юзеров с зарплатой 900 .

Выберите юзеров в возрасте 23 года.

Выберите юзеров с зарплатой более 400 .

Выберите юзеров с зарплатой равной или большей 500 .

Выберите юзеров с зарплатой НЕ равной 500 .

Выберите юзеров с зарплатой равной или меньшей 500 .

Источник

Оцените статью