⊗ppSpPDNP 61 of 83 menu

Named Placeholders in PDO in PHP

For convenience, you can use named placeholders, where the order of variables in the array does not matter. Let's see how to work with them.

Suppose we again have the following variables:

<?php $min = 1; $max = 5; ?>

Let's create an SQL query using named placeholders. Their syntax is: a colon, followed by the placeholder name. Let's use them in the query:

<?php $sql = 'SELECT * FROM users WHERE id>:min and id<:max'; ?>

Prepare the query:

<?php $res = $pdo->prepare($sql); ?>

Execute the query by passing it an associative array as parameters, where the keys are the names of the placeholders in the SQL query, and the values are the corresponding variables:

<?php $res->execute([ 'min' => $min, 'max' => $max ]); ?>

We can view the result:

<?php while ($row = $res->fetch()) { var_dump($row); } ?>

Let's put it all together and get the following code:

<?php $min = 1; $max = 5; $sql = 'SELECT * FROM users WHERE id>:min and id<:max'; $res = $pdo->prepare($sql); $res->execute([ 'min' => $min, 'max' => $max ]); while ($row = $res->fetch()) { var_dump($row); } ?>

Given a variable:

<?php $age = 30; ?>

Find all users whose age is equal to the value specified in the variable.

Given variables:

<?php $age1 = 20; $age2 = 30; ?>

Find all users whose age falls within the range specified by the variable values.

Given variables:

<?php $age1 = 20; $age2 = 30; $salary1 = 1000; $salary2 = 2000; ?>

Find all users whose age AND salary fall within the range specified by the variable values.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline