For Connecting SQLite database with PHP, you must have PHP and SQLite installed on your system.
If sqlite is not installed, first install sqlite by using the following command:
sudo apt-get install sqlite3 libsqlite3-dev
sudo apt install php-sqlite3
Follow the steps given below systematically:
{ "autoload": { "psr-4": { "App\\": "app/" } } }
Open the Command prompt, go to the phpsqliteconnect and execute the following code:
composer update
Now, you will get the following message:
if composer is not installed then first install composer
apt install composer
Now create a file name "index.php" in the root folder "phpsqliteconnect", having the following code:
<?php require 'vendor/autoload.php'; </textarea></div> <hr/> <h2 class="h2">Establish connection with SQLite database</h2> <p>Create a new file "Config.php" inside the app folder, having the following code:</p> <div class="codeblock"><textarea name="code" class="php"> <?php namespace App; class Config { /** * path to the sqlite file */ const PATH_TO_SQLITE_FILE = 'db/rookienerd.db'; }
The constant PATH_TO_SQLITE_FILE is used to store the path to the sqlite database file inside the db folder.
Now, create a new SQLiteConnection.php file and add the SQLiteConnection class as follows:
<?php namespace App; /** * SQLite connnection */ class SQLiteConnection { /** * PDO instance * @var type */ private $pdo; /** * return in instance of the PDO object that connects to the SQLite database * @return \PDO */ public function connect() { if ($this->pdo == null) { $this->pdo = new \PDO("sqlite:" . Config::PATH_TO_SQLITE_FILE); } return $this->pdo; } }
After having all classes in places, you use the following command to generate the autoload file:
composer dump-autoload -o
<?php ini_set('display_errors', 1); error_reporting(E_ALL ^ E_NOTICE); require 'vendor/autoload.php'; use App\SQLiteConnection; $pdo = (new SQLiteConnection())->connect(); if ($pdo != null) echo 'Connected to the SQLite database successfully!'; else echo 'Whoops, could not connect to the SQLite database!'; ?>
Now, open the localhost an your browser http://localhost/phpsqliteconnect/
Connection is established successfully. You can also see the tree sturcture by by using the tree command: