Creating a table

In the following PHP code, we will create a database table.
<?php
$dbhandle = sqlite_open('db/test.db', 0666, $error);
if (!$dbhandle) die ($error);

$stm = "CREATE TABLE scanftree(Id integer PRIMARY KEY," . 
       "Name text UNIQUE NOT NULL)";
$ok = sqlite_exec($dbhandle, $stm, $error);

if (!$ok)
   die("Cannot execute query. $error");

echo "Database scanftree created successfully";

sqlite_close($dbhandle);
?>


Explaintation



$dbhandle = sqlite_open('db/test.db', 0666, $error);
The sqlite_open() function opens a SQLite database. The function has three parameters. The first parameter is the filename of the database. According to the documentation, the second parameter is ignored currently. The 0666 is the recommended value. If we cannot open the database, an error message is put into the $error variable.

if (!$dbhandle) die ($error);
The sqlite_open() function returns a database handle on success or FALSE on error. The die() function outputs an error message and terminates the script.

$stm = "CREATE TABLE scanftree(Id integer PRIMARY KEY," . 
    "Name text UNIQUE NOT NULL)";
The $stm variable holds the SQL statement to create a Friends database table. Note that there are two strings concatenated with the dot operator.

$ok = sqlite_exec($dbhandle, $stm, $error);
The sqlite_exec() executes a result-less statement against the database. The first parameter is the database handle, that we obtained with the sqlite_open() function. The second parameter is the statement, that we are about to execute. And the last parameter is the possible error message. This is usually due to a syntax error. The function returns TRUE for success or FALSE for failure.

if (!$ok)
   die("Cannot execute query. $error");
We check for possible errors. There could be two types of errors. SQL syntax error or insufficient permissions.

echo "Database Friends created successfully";
If all went OK, we print a message 'Database scanftree created successfully'. If there is some error, this message is not printed, because the die() function terminates the execution of the PHP script.

sqlite_close($dbhandle);
We close the database handle. It is not necessary to do it explicitly. PHP language does it automatically. But it is a good programming practice to do it.