Tutorial by Examples

Since PHP 5.0, PDO has been available as a database access layer. It is database agnostic, and so the following connection example code should work for any of its supported databases simply by changing the DSN. // First, create the database handle //Using MySQL (connection via local socket): $d...
SQL injection is a kind of attack that allows a malicious user to modify the SQL query, adding unwanted commands to it. For example, the following code is vulnerable: // Do not use this vulnerable code! $sql = 'SELECT name, email, user_level FROM users WHERE userID = ' . $_GET['user']; $conn->...
There are two ways to connect to a MySQL/MariaDB server, depending on your infrastructure. Standard (TCP/IP) connection $dsn = 'mysql:dbname=demo;host=server;port=3306;charset=utf8'; $connection = new \PDO($dsn, $username, $password); // throw exceptions, when SQL error is caused $connection-...
Database transactions ensure that a set of data changes will only be made permanent if every statement is successful. Any query or code failure during a transaction can be caught and you then have the option to roll back the attempted changes. PDO provides simple methods for beginning, committing,...
We start off with $db, an instance of the PDO class. After executing a query we often want to determine the number of rows that have been affected by it. The rowCount() method of the PDOStatement will work nicely: $query = $db->query("DELETE FROM table WHERE name = 'John'"); $count = ...
You may often find the need to get the auto incremented ID value for a row that you have just inserted into your database table. You can achieve this with the lastInsertId() method. // 1. Basic connection opening (for MySQL) $host = 'localhost'; $database = 'foo'; $user = 'root' $password = ''...

Page 1 of 1