Tags
PHP , SQLite
Asked 7 years ago
8 Feb 2017
Views 1408
jaydeep

jaydeep posted

How to use SQLite with PHP?

How to use SQLite with PHP?
Rasi

Rasi
answered Nov 30 '-1 00:00

sqlite_open function will open the connection for SQLite in PHP

$dbhandle = sqlite_open('sqlitedb');



<?php
$dbhandle = sqlite_open('exampledb');
$result = sqlite_array_query($dbhandle, 'SELECT id, name,email FROM employee', SQLITE_ASSOC);
foreach ($result as $entry) {
    echo 'Name: ' . $entry['name'] . '  E-mail: ' . $entry['email'];
}
?>


sqlite_array_query will run one or more than one SQLite query .

Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

PDO is good way to connect with database in PHP

PDO construct connect to SQLite , argument should be database file name

$db = new PDO('sqlite.db');


if you use 'sqlite::memory:' instead of file name . it use SQLite memory . data will flushed at every run . so its can be temporary use.

$db = new PDO('sqlite::memory:');


exec function is used to execute the query .

$db->exec("CREATE TABLE strings(a)");

will create a table

you can also prepare statement and run it when data ready

$insert = $db->prepare('INSERT INTO strings VALUES ("abc")');
$insert->execute();


how to fetch data in SQLite with PHP

$result=$db->query('SELECT a from strings')
$data=$result->fetchAll();


final code ::
sqlite.php

$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES ("abc")');
$insert->execute();
print_r($db->query('SELECT a from strings')->fetchAll());
Post Answer