error to db
The code is an example of custom error handling in PHP that save the error messages into a database. It connects to a MySQL database using the PHP Data Objects (PDO) extension, which allows for a more secure and flexible way to interact with databases. The script sets the connection details such as the host, database name, user and password.
It then defines a function saveError() that takes two parameters: $errno, which is the error number and $errstr, which is the error message. The function then uses a prepared statement and the PDO object to insert the error message into the 'errors' table in the database. The function also echoes a message with the error number and error message.
The script sets the custom error handler function saveError() to be used with the set_error_handler() function. This function takes two parameters: the name of the function to be used as the error handler and the error level to be handled by the error handler. In this case, it is set to handle E_WARNING level errors.
After this, the code triggers an error by calling a require statement to include a file that does not exist, 'fileDoesNotExist.txt', this will throw an error because the file does not exist. The error handler function saveError() will be called, it will save the error message "fileDoesNotExist.txt" into the errors table and also display the message 'Error: fileDoesNotExist.txt' to the browser.
It is important to note that, the table errors should be created before running the script. The code provided a query to create the table.
<?php
/*
* run this query in your database
* CREATE TABLE `errors` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`errstr` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
*/
// Save error messages into database
// connect to database pdo
$dsn = 'mysql:host=localhost;dbname=php';
$user = 'root';
$pass = 'root';
$con = new PDO($dsn, $user, $pass);
// function to save error messages into database
function saveError($errno, $errstr) {
global $con;
$sql = 'INSERT INTO errors (errstr) VALUES (:errstr)';
$stmt = $con->prepare($sql);
$stmt->execute(array(
':errstr' => $errstr,
));
echo 'Error: ' . $errstr;
}
// set error handler
set_error_handler('saveError', E_WARNING);
// trigger error on false require
require ('fileDoesNotExists.txt'); // this will throw an error because the file does not exist
// create a table with auto increment id and errstr and utf8