SQLite with PHP

This is about using SQLite in PHP application.

CodeLearner

5/18/20232 min read

<?php

$db = new SQLite3('db/sampleDB.db');

if(!$db){

echo "Error connecting to database.";

}

?>

Steps for using SQLite in PHP

Step 1

Download
DB Browser for SQLite https://sqlitebrowser.org/dl/

Step 2

Create a DB file by clicking New Database menu and
name it what you want. (I will be naming it sampleDB)

Step 3

Create a Table
name it what you want. (I will be naming it users). Look for the Execute SQL and paste that create query.

Step 4

First!

Step 5

I hope it helps.

Step 6

Assuming that the log in page is done:

Enable extension=sqlite3
in PHP.INI file of your PHP server

Use your existing PHP application with login page
or create a new one.

Create PHP file for SQLite connection. Name it what you want. (I will be naming it conn). You can use any Text Editor or IDE. I will be using VS Code.

Insert this code to PHP file responsible for connecting to SQLite database: (conn.php)

Note: ‘db’ is the name of the folder where I save my sampled.db file or my database

Assuming that the connection file is done:

Create PHP file for handling login. Name it what you want. (I will be naming it login_controller)

Login_controller code:

<?php

session_start();

require_once 'includes/conn.php';


if (isset($_POST['loginButton'])) {

$username = SQLite3::escapeString($_POST['userName']);

$password = SQLite3::escapeString($_POST['passWord']);

$path = $_POST['path'];


$sql = "SELECT * FROM users where username = '$username'";

$query = $db->query($sql);

$row = $query->fetchArray(SQLITE3_ASSOC);

if ($row['username'] = "") {

$_SESSION['error'] = 'Username or Password <b>INCORRECT</b>';

}

else {

if (password_verify($password, $row['password'])) {

$_SESSION['admin'] = $row['id'];;

} else {

$_SESSION['error'] = 'Username or Password <b>INCORRECT</b>';

}

}

} else {

$_SESSION['error'] = 'Input admin credentials first';

}


header('location: index');

?>

SQLite3::escapeString — Returns a string that has been properly escaped

SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both