⊗ppSpPDVB 63 of 83 menu

Positional Binding of Variables in PDO in PHP

You can bind variables to the query one by one. This is done using the bindValue method. Then the resulting query is executed, but in this case, nothing is passed to execute.

Such binding allows you to specify the exact type of the variable, canceling the auto-wrapping in quotes for numeric values. Let's see how it's done. Suppose we have two variables, a string and a numeric one:

<?php $name = 'name1'; $age = 25; ?>

Let's prepare the query:

<?php $sql = 'SELECT * FROM users WHERE name=? or age=?'; $res = $pdo->prepare($sql); ?>

Now let's bind the variables to the query using the bindValue method. The first parameter of the method specifies the position number in the query, the second parameter is the variable name, and the third specifies the variable type (numeric or string):

<?php $res->bindValue(1, $name, PDO::PARAM_INT); $res->bindValue(2, $age, PDO::PARAM_STR); ?>

Let's execute the query:

<?php $res->execute(); ?>

Let's look at the result:

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

Given variables:

<?php $name1 = 'name1'; $name2 = 'name2'; ?>

Get users whose name matches the value of the first or the second variable.

Given variables:

<?php $age1 = 21; $age2 = 22; ?>

Get users whose age matches the value of the first or the second variable.

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