Inserting database errors back into database - php

What I was trying to do is inserting all query errors into a database, but, it doesnt work. I wanted to do this:
<?php
include('db_settings.php');
$query = $conn->query("mysql_query here");
if (!query) {
$error = $conn->error;
$log_error = $conn->query("INSERT INTO tab (log) VALUES ('$error')");
}
?>
However, this does not work, the error is not being submitted into the db.
Does any of you know some workaround for this?
(before someone asks, all parameters of DB and variables are correct).

You simply shouldn't do that.
Do not try to use a medium that failed you that very instant!
Let's take one of your recent questions: The very error message that troubled you here, Mysqli Commands out of sync will prevent your wunderlogging from functioning! Your database won't get back to sync by magic! And thus will effectively prevent you from logging its own error. And so you simply will never have an idea it occurred.
Let errors to be logged, and then you'll be able find them all.
add these three lines at the top of your code,
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and then check the server error log.
This is how everyone is doing it and there is no reason to devise such an awkward and illogical device.

Related

Can the mysql_error() function be disabled in php?

I came across in a project of about 900 files with 3 millions lines of code, and my boss asked me to find a solution to prevent mysql_error() to show errors.
This is the syntax
mysql_query() OR die(mysql_error())
So, how can I disable the mysql_error() from showing errors?
function mysql_own_error($debug = false){
$msg = mysql_error();
if($debug){
echo $msg;
}else{
// Function to log errors here.
}
}
With that you can set a global debug-variable $debug. Only if that is true output the error msg.
Now replace every mysql_error() with mysql_own_error($debug). There are Editors that can do suche replaces fast.
With that you will prevent the mysql_error() from showing errors publicly but you can still debug the code if you need to.
If you're still having errors then your project is not finished yet.
One way would be to do a site-wide find/replace on your files and replace the OR die(mysql_error()) with an # in front of mysql_error() like so: OR die(#mysql_error()).
Placing an # in front of a function call suppresses error messages. But use it carefully, this is not always a good solution.
Read this post which links to this article to know if it's a good solution for you.
I would change all OR die() occourrences to a custom error-handling function, then if you get an error you will still know about it without displaying them to users.
Yes, it would take a lot of time, but a good project takes a lot of time.
Check this article to create your own error-handling function and this other one to Enable PHP error logging via .htaccess, they really helped me.

Mysqli connection warning showing if connection details are bad

I have some code that allows a user to input details for their database on their server. After they submit the details, the code checks a connection to the database to see if valid details were entered. I want it to give outcomes of variables being true if the connection either works or does, like this:
$mysqli = new mysqli($_POST['dbHost'],$_POST['dbUser'],$_POST['dbPassword'],$_POST['dbName']);
if ($mysqli->connect_errno) { $badDetails = true; }
else { goodDetails = true; }
Problem is, if the details are indeed incorrect, it shows a PHP warning from the first line of the code above giving 'Unknown MySQL server host'.
What is the way around this? I don't want PHP throwing it's own visible error for this, I want to deal with the error myself.
You should not worry about visual errors. In a production environment, these should be turned off in the ini, and all errors should go to a log on the server instead of just to the screen.
This is configured with the display_errors setting and error_reporting()
Many frameworks override the PHP error handler with a custom implementation to display error in a pretty way, depending on their severity.
To achieve this, you can override the PHP error handler
As seen in the manual one can register custom handlers for regular errors and exceptions. And it is also possible to trigger an user defined error.
Just use a die()
$mysqli = new mysqli($_POST['dbHost'],$_POST['dbUser'],$_POST['dbPassword'],$_POST['dbName']) or die("Database Connection Failed");
A quick, dirty method would be error supression:
$con = #mysqli_connect( /* info */ );
Note that you should not keep this there, as this will suppress all errors, and mysqli can have multiple errors that you might need to know about.
Though I would check the host variable first, to see why the error is caused. You can also use die.
$con = mysqli_connect(/* info */) or die ("SQL Error!");
As far as where to look, try seeing that the host var is actually set and check it's value:
if (!isset($_POST['dbHost'])) {
echo "Host var not set!";
} else {
echo "Host var set: " . $_POST['dbHost']
}

PDO error handling and storing errors in database

How would I go about getting PDO statements to generate a safe error message? I don't want the user to see the error message. I want them to get directed to a page that says a clean message, "Whoops something unexpected happened!". I would also like to log the errors in a database to review and catch errors others are generating.
I'm using PHP and MySQL.
I found that when you make your connection you can set your error handling like this.
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Anyone do anything like this before?
So this is just a suggestion as I have never tried this but after thinking about it a bit I think it would be an interesting option to explore. As I am fairly new to PHP & PDO I'm sure there are other and better ways.
Perhaps you could try using the try function of PHP and then instead of echo'ing (if failed) the PDOException you could run another function that prints it to a text file. Something like.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
$strFileName = 'whatever.txt';
if(!is_writable($strFileName))
die('Change permisions to ' . $strFileName);
$handle = fopen($strFileName, 'a+');
fwrite($handle, "\r" . $e->getMessage() . "\r");
fclose($handle);
}
?>
This way you would avoid a DB connection (which is the problem I guess) but still save the error.
You would perhaps want to omit the echo'd text after die within the if statement.
I think it is better to write your logs to a file, instead of a database. Especially since you want to log PDO errors, which indicate something is wrong with your database connection.
You can show the user a nice error page by catching your errors. You can redirect your users to your error page then, in case something went wrong.
You have to understand that PDO do not generate a "safe" or "unsafe" error message. It does generate an error message. That's all. The rest is is the responsibility of site-wide PHP settings.
PDO is not the only source of errors. Why care of PDO errors only? Why not to handle ALL errors the same way?
Want errors logged? It's a matter of one PHP ini setting.
Want errors not to be displayed? It's a matter of one PHP ini setting.
Want generic error page to be shown? It's a matter of simple function that will handle all errors at once.
Everything can be done proper and straight way, without wrapping every statement into try catch. Without writing into log manually. Without even single additional line of code.
You need to set up PHP error handling, not PDO.
And of course, it makes absolutely no sense in trying to store a database error in the same database that failed you right now. Errors have to go into error log on a live server and on screen - on a local development PC.
Anyone do anything like this before?
Sure. Every single one of 1000000s sites in the world. The way described above.

What is proper way to handle mysql errors with php?

What is the "proper" way to deal with errors when manipulating a sql database with php?
What Im currently doing looks like this:
$connection = new mysqli('hostname', 'user', 'pass', 'database');
if ($connection->connect_errno) {
reportError("DB_CONNECTION_ERROR", $connection->connect_errno, $connection->connect_error);
displayError("DB_CONNECTION_ERROR");
}
$stmt = $connection->stmt_init();
$q = "query";
$stmt->prepare($q);
$stmt->bind_param('s', $username);
$stmt->execute();
reportError() is part of an error handling file I wrote and logs the error in a database
displayError() is part of the same file and tells the page what to display (as opposed to displaying the actual error).
However Im not sure of how to check for other errors, such as whether a statement was successfully prepared or whether a query was successful. Any recommendations appreciated!
Don't you find it quite odd to write database connection errors... into database?
I see also no point in having custom displayError() function. It should be generic _503() function, sending corresponding header along with general excuses.
I see no point in having custom logError() function either. PHP quite capable to log errors itself. trigger_error() serves me best.
Im not sure of how to check for other errors, such as whether a statement was successfully prepared
Ah, this one. Exceptions.
Mysqli should throw an exception if something went wrong. See mysqli_sql_exception for more details.
In your client code, you can then wrap your code in try/catch blocks:
try {
} catch (Exception $e) {
}
Sometimes, there are exceptions that can't be solved within a try/catch block, for example, the database server is down, and a site that is heavily reliant on the database would not be able to function anyway.
For those very critical problems, you can allow the exception to bubble upwards. You should then set an exception handler at the beginning of your script to catch those exceptions, notify the administrator and do some logging, then display an 500 error page to the user.

how to get a detailed error report when a php-mysql script fails?

How do i get a detailed error description during a php-mysql script run?
I have the following statements where the script fails and displays the custom error message - the contents of the "or die".
I want to get the actual error from MySQL (instead of the custom error i have mentioned), which would give better idea about the scenario - whether its a database issue or server connectivity issue etc..
this is the code i have where i need to enhance the error reporting
$query = "SELECT * FROM table_name";
$result = mysqli_query($db_conn, $query)
or die('Connected to database, but querying failed');
thanks!
Check out mysql_error function.
Have a look at the manual page for mysqli_error. In the section "Procedural style" you'll find a complete example that shows how to set up the database connection and querying the database, both steps with error handling.
If you want detailed error information from your scripts you can put the lines
error_reporting( E_ALL );
ini_set('log_errors', true);
ini_set('error_log', '/tmp/php-errors.log');
at the start of your code. That way all errors coming from PHP will be written into the log file. Make sure that the path to the log file exists (/tmp is only an example) and is writable by the web server, otherwise the errors will be silently discarded.
As a side note: While the "or die()" pattern is good for small examples, you should not use it in production code.
I prefer using PDO, and having PDO throw an exception.
you could insert the query into the query page on phpmyadmin that is if you are using it. But this wont tell you if the errors are with the variables

Categories