⊗ppSpPDPP 60 of 83 menu

Positional Placeholders in PDO in PHP

Let's figure out how to work with positional placeholders. Suppose we have two variables that we would like to insert into the query:

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

Suppose we want to insert our variables in the following way:

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

However, doing it this way is not safe. Therefore, instead of inserting variables directly, we will replace them with positional placeholders, which are question marks:

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

Now let's execute the command that will prepare the query:

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

Now let's execute the query by passing it an array containing our variables as parameters. In this case, the variables will be inserted into the query in the order they are specified in the array:

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

After that, we can get the query 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>? and id<?'; $res = $pdo->prepare($sql); $res->execute([$min, $max]); while ($row = $res->fetch()) { var_dump($row); } ?>

Given variables:

<?php $age = 30; $salary = 1000; ?>

Find all users whose age or salary equals the values specified in the variables.

Try to perform an SQL injection on your code. Make sure it doesn't work.

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