⊗ppSpPDQu 57 of 83 menu

Database Queries with PDO in PHP

The variable $pdo, which we obtained after connecting to the database, is an OOP object. This object has a special method query that executes SQL queries. Let's make a test query to our table:

<?php $res = $pdo->query('SELECT * FROM users'); ?>

The variable $res will store the query result. To get one row from the result, you need to use the method fetch:

<?php $row = $res->fetch(); var_dump($row); // first row $row = $res->fetch(); var_dump($row); // second row $row = $res->fetch(); var_dump($row); // third row ?>

When the rows run out, the method will return null. Therefore, it is convenient to get rows in the following loop:

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

For example, let's output user names in separate paragraphs:

<?php while ($row = $res->fetch()) { echo '<p>' . $row['name'] . '</p>'; } ?>

Let's put all the code together:

<?php $res = $pdo->query('SELECT name FROM users'); while ($row = $res->fetch()) { echo '<p>' . $row['name'] . '</p>'; } ?>

Output the salary of all users from the users table.

Output all records in the format name: age.

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