Inserting data in SQLite database using PHP



In the following example, we will insert some data into the scanftree database.
<?php
   
$dbhandle = sqlite_open('db/test.db', 0666, $error);

if (!$dbhandle) die ($error);
    
$stm1 = "INSERT INTO scanftree VALUES(1,'ankit', 'F')";
$stm2 = "INSERT INTO scanftree VALUES(2,'kumar', 'M')";
$stm3 = "INSERT INTO scanftree VALUES(3,'singh', 'M')";

$ok1 = sqlite_exec($dbhandle, $stm1);
if (!$ok1) die("Cannot execute statement.");

$ok2 = sqlite_exec($dbhandle, $stm2);
if (!$ok2) die("Cannot execute statement.");

$ok3 = sqlite_exec($dbhandle, $stm3);
if (!$ok3) die("Cannot execute statement.");

echo "Data inserted successfully";

sqlite_close($dbhandle);

?>
We insert some data. We don't retrieve any data. Therefore we use again the sqlite_exec() function.
$stm1 = "INSERT INTO scanftree VALUES(1,'ankit', 'F')";
$stm2 = "INSERT INTO scanftree VALUES(2,'kumar', 'M')";
$stm3 = "INSERT INTO scanftree VALUES(3,'singh', 'M')";
Here we have three statements that will insert three rows into the scanftree database.
$ok1 = sqlite_exec($dbhandle, $stm1);
if (!$ok1) die("Cannot execute statement.");
We execute the first statement. If something goes wrong, the script is terminated.

What if we wanted to add a name like ankit's ?
The single quote ' character belongs to some unsafe characters. Using them could lead to problems. We must properly escape them.
$name = "ankit's";
$name_es = sqlite_escape_string($name);
$stm = "INSERT INTO scanftree VALUES(4,'$name_es', 'M')";

$name_es = sqlite_escape_string($name);
we use the sqlite_escape_string() function. to change ankit's to ankit''s