Accessing SQLite Databases in PHP using PDO
PDO or PHP Data Objects is a data abstraction layer, i.e. it provides uniform methods to access different types of databases, as a result switching between or moving to a different database system is relatively easier. So, in simple language the code to access a SQLite db will also work for MySQL db with minor changes. PDO provides a plethora of database drivers like MySQL, Oracle, Postgre SQL, SQLite, Firebird, etc. In this article we will look at accessing a SQLite db using PDO.
PDO & driver for SQLite is enabled by default from PHP version 5.1.0 onwards, if not so use the following command to install PDO:
Windows users please refer to the official PDO installation documentation at http://www.php.net/manual/en/pdo.installation.php.
Let's get our hands dirty with a little code, first let's try to list all the different database drivers available to PDO, see the code snippet below:
PDO needs a DSN (Data Source Name) to connect to, for SQLite the DSN is just the path to the database file. Follow the code snippet below:
Now, we have connected to the database and created a table, next let's look at a few more basic things required to work with databases, like preparing queries, using placeholders, etc.
Prepared queries help optimizing code when the same query is executed multiple times with changes in the values, similarly placeholder help you prevent SQL injection attacks on your code by automatically add quotes to values. Let's look at the code snippet below:
That's all you need to get started.
Re: Accessing SQLite Databases in PHP using PDO
I really like this but one suggestion is you should be using <?php and not <? because these days default PHP installation does not have the shorter version enabled by default.
|All times are GMT +5.5. The time now is 10:05.|