Knowledge Base Hub

Browse through our helpful how-to guides to get the fastest solutions to your technical issues.

Home  >  How-Tos  >  How can I connect to SQLite using PHP?
Top Scroll

How can I connect to SQLite using PHP?

 2 min

This article will guide you on how to connect to the SQLite database using PHP.

Steps to connect to SQLite using PDO (PHP Data Objects) :

PDO (PHP Data Objects) withdraws database access and allows you to create code that is capable to handle different types of databases. SQLite is a database type that supports PDO.

Perform the following steps to connect SQLite using PDO :

1. Using the following PHP code, connect to the SQLite database. Replace username with MilesWeb Hosting account username, path with the path of the database file, and filename with the name of the database file:

<?php

   $myPDO = new PDO('sqlite:/home/username/path/filename');

?>

Suppose, if you have a SQLite database named books.db in your home directory, and the username is example, then you can use the following statement :

<?php

   $myPDO = new PDO('sqlite:/home/example/books.db');

?>

2. Once the code connects to the SQLite database, you can run SQL queries and perform other operations. As an example, the following PHP code runs a SQL query that extracts the last names from the employees table, and stores the result in the $resultvariable :

<?php

   $result = $myPDO->query("SELECT lastname FROM employees");

?>

This is one method to access the result set’s values and print them :

<?php

   foreach($result as $row)

   {

       print $row['lastname'] . "\n";

   }

?>

For more information on PDO visit :
http://www.php.net/manual/en/book.pdo.php.

This is the easiest way to connect to SQLite using PHP.

Also Read :

Steps to Create a PHP Redirect

How To Create MySQL Tables In phpMyAdmin?

Steps to Enable PHP Error Logging & Automation

For our Knowledge Base visitors only
Get 10% OFF on Hosting
Special Offer!
30
MINS
59
SECS
Claim the discount before it’s too late. Use the coupon code:
STORYSAVER
Note: Copy the coupon code and apply it on checkout.