We will create the database and connection object.
$my_conn = new PDO('sqlite:my_student.sqlite3');
Database file path
The database path we can set by using this code. We can change the database file extension also. Use one of the line.
//$my_conn = new PDO('sqlite:my_student.sqlite3');// same path as file execution
//$my_conn = new PDO('sqlite:D:\\sqlite-data\\my_student.db');// different path
$my_conn = new PDO('sqlite:'.dirname(__FILE__).'/test.db'); // same location
We will use $my_conn to create our table with some sample data.
SQLite database connection from PHP PDO and adding error mode handling by using configuration A2
Setting the Error Mode in PDO
By default, PDO does not throw exceptions for errors, which means you might not notice issues immediately.
Here are the error modes.
PDO::ERRMODE_SILENT:
This is the default error mode.
PDO will set an error code for you to check manually, but it won't interrupt script execution or throw any exceptions.
PDO::ERRMODE_WARNING:
In this mode, PDO will emit a PHP warning whenever an error occurs.
The script will continue executing, but you'll be notified of the issue through warnings.
PDO::ERRMODE_EXCEPTION:
This mode causes PDO to throw a PDOException whenever an error occurs.
This is the most robust option, as it allows you to handle errors using try-catch blocks.
It is often recommended for better error handling and debugging.
As a developer we will use ERRMODE_EXCEPTION inside our try catch code block. This we will keep inside our config.php file to connect from other files.