Handling MySQL errors in PHP [duplicate] - php

This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Closed 2 years ago.
While developing my website I use mysql_error() to display errors so I know how to fix them.
My question is... when the website goes live, how should I handle the errors, because I do not want the user to see the errors but instead see a user friendly message like "Oops, something went wrong".

Firstly, I'd strongly recommend moving from the deprecated mysql_ functions to either one of the MySQLi or PDO classes. Both are far more secure, and being maintained for current and foreseeable future versions of PHP.
Some possible solutions to displaying an error could be:
$sql = new mysqli($host, $user, $password, $database);
$query = //your query
//Option 1
$result = $sql->query($query) or die("Something has gone wrong! ".$sql->errorno);
//If the query fails, kill the script and print out a user friendly error as well
//as an error number for them to quote to admins if the error continues to occur,
//helpful for debugging for you, and easier for users to understand
//Option 2
$result = $sql->query($query);
if($result) {
//if the query ran ok, do stuff
} else {
echo "Something has gone wrong! ".$sql->errorno;
//if it didn't, echo the error message
}
You could also use the PHP error_log function to put a new error into the error log which could contain the full $sql->error details for admins to view, and completely skip the $sql->errorno printout. For more info on error logging, check the PHP Docs

Normally you want to log these errors in a live enviroment (meaning, you write the error message and some further infromation like time, ip, .. to a file)
On the userside you should also provide the User some feedback, so print a nice error message so that the user knows that something went wrong.
Just use Google to find some Logger-libraries. Mostly, they can be configured to change behaviour in live and development enviroment!
You might also have a look at: https://www.php-fig.org/psr/psr-3/

While developing your website, you should not use mysql_error(), because you should not use any of the mysql_* functions, because they are deprecated.
The most basic error handling is to throw an Exception. The exception handler should log the error message along with a stack trace and output an error page.

What you need is to handle the answer you receive from the SQL query. Like if success or if error.
Like this:
<?php
$response = 0;
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno()){
$response = "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform a query, check for error
if (!mysqli_query($con,"INSERT INTO Persons (FirstName) VALUES ('Glenn')")){
$response = "Error description: " . mysqli_error($con);
}
mysqli_close($con);
echo $response;
?>
Then in your Frontend side, you can give a format to your response, with a jQuery plugin, or some framework. I recommend to use: jquery confirm.
References:
https://www.w3schools.com/php/func_mysqli_error.asp
https://craftpip.github.io/jquery-confirm/
If you want to handle the specific error, try it by detecting the exactly error number code.
https://dev.mysql.com/doc/refman/5.5/en/server-error-reference.html
https://www.php.net/manual/es/mysqli.errno.php

You can use:
if (mysqli_error($conn)) {
$error = 'Oops something went wrong!';
}
echo $error;
The $conn stands for the database connection through which the query was carried out.

Related

Does error handling on every query affects performance?

Hello i'm wondering if putting error handler in every query especially Inserts and Updates affects the performance of web application with huge database? if not how can i use try catch properly on every query to stop the process and inform the user? is it possible to rollback inserted data?
sample error logging:
$query = mysqli_query($conn, "insert into `table`(`fields`) values('$variable')");
if(!$query){
write_mysql_log("logs here", $conn);
echo "<script>alert('Error message, like something went wrong'); window.location = 'page.php';</script>";
}
No. You should be checking for errors from the query.
The check for errors is entirely separate from running the query itself. The query will still return errors, even if you don't check for them.

mysql dies everytime I try to create a new table

I am attempting to create new tables every time I post to this method, but for some reason I can not figure out why it dies.
<?php
$host = "127.0.0.1";
$username = 'cotten3128';
$pwd = 'pwd';
$database = "student_cotten3128";
$pin = $_REQUEST['pinSent'];
$words = $_REQUEST['resultSent'];
$tableName = $pin;
$db = new mysqli($host, $username, $pwd, $database);
if ($sql = $db->prepare("CREATE TABLE $pin (id INT(11) AUTO_INCREMENT);")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die('Could not create table');
}
for($i=0;$i<count($words);$i++){
if($sql = $db->prepare("INSERT INTO ".$pin.$words[$i].";")) {
$sql->execute();
$sql->close();
}else{
echo $mysql->error;
die("Could not add data to table");
}
}
mysqli_close();
?>
Any help or insight would be greatly appreciated.
The intention of my post is to help you finding the issue by yourself. As you did not added much information I assume my post is helpful for you.
Based on the code you have shared I guess you mean one of your called die() functions is executed.
Wrong function call
As Jay Blancherd mentioned mysql_close is the wrong function. You rather have to use mysqli_close as you created a mysqli instance.
Beside of that mysql_* is deprecated and should not be used anymore.
Debugging Steps
Not only for this case but in general you should ask yourself:
Is there an error message available? (Frontend output, error log file, ...)
YES:
What's the message about?
Is it an error you can search for? E.g. via a search engine or the corresponding documentation?
Look up in the bug tracker (if available), by the software developer of the software you are using, and if it has not been reported yet report the issue.
NO: (if none error message available OR you cannot search for it as it is a custom error message)
Search in the files of the software you are using for the error message and start a core-debugging.
STILL NO SOLUTION?:
Ask on stackoverflow.com e.g. and tell your issue and the steps you have performed to find and fix the bug. Post only as much code as necessary plus use a proper format.
Debugging in your case:
In order to narrow down the scope. Which of the die() is executed? Depending on that echo the query to execute just before it actually is executed. Then copy the SQL query to an SQL editor and look at it syntax. After that you probably know the problem already.

PHP - Error handling while querying mysql

I am new to web development, so probably there is something I am doing it wrong.
I am using webmatrix for development and playing around with StarterSite sample that webmatrix provides.
In one of the php file (header.php) there is a query to mysql using mysqli extension. I have changed the tablename to some non existent table to simulate error condition. The problem is, after below statement -
$statement->execute();
the script stops.
I inserted a echo statement after execute and that echo string is not displaying on webpage. However when I correct the table name, the echo string after execute is displayed on webpage. So I think the script stops executing after execute when the table name is wrong. I have two questions. How do I stop script from stop executing like this? Secondly How to know for sure that script has stopped executing at some particular statement?
For second part of question, I checked the log file and tracelog file in IISExpress folder. There is no mention of any error, probably because error happened in MYSQL. However, in my MYSQL folder there is no log file, so not sure how to check mysql log.
If I have missed anything, please let me know.
Regards,
Tushar
You should read about mysqli error handling.
Basic error handling example OOP:
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Procedural:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
It depends on what you're logging. In the error log you can define what's being logged. I think you can control the strict mode of the error in the php.ini which will automatically throw error into the access_log or error_log or apache log file.
The trick is to use $mysqli->error in every step of the mysqli querying and db connects to ensure you're getting proper error messages in detail whether to debug, improve the code or to do it correctly.
Here is an example of using $mysqli->error in querying the database.
$result = $mysqli->query($query);
if (!$result and $mysqliDebug) {
// the query failed and debugging is enabled
echo "<p>There was an error in query: $query</p>";
echo $mysqli->error; //additional error
}
You can also use a method where you define mysql error to be true in db conn
// define a variable to switch on/off error messages
$mysqliDebug = true;
// connect to your database
// if you use a single database, passing it will simplify your queries
$mysqli = #new mysqli('localhost', 'myuser', 'mypassword', 'mydatabase');
// mysqli->connect_errno will return zero if successful
if ($mysqli->connect_errno) {
echo '<p>There was an error connecting to the database!</p>';
if ($mysqliDebug) {
// mysqli->connect_error returns the latest error message,
// hopefully clarifying the problem
// NOTE: supported as of PHP 5.2.9
echo $mysqli->connect_error;
}
// since there is no database connection your queries will fail,
// quit processing
die();
}
#ref: https://www.daniweb.com/web-development/php/code/434480/using-phpmysqli-with-error-checking

Basic php/mysql query struggles

I am frustrated and I am beginning to wonder if there is some catch with my hosting company that might be causing this issue. I have done this type of thing before (not with this hosting company) so I am at a loss.
<?php
$q = "SELECT * FROM sunsetUsers";
$r = #mysqli_query($dbh, $q);
if ($r) {
echo 'good job';
} else {
echo 'you suck';
}?>
The connection info is being called in the header and it works. It will connect to the database and supply me with a good message when I tell it to. Yet, when I try to execute a simple query, I get nothing. No errors at all other than it tells me, "you suck." Heh...which is what it should do when the query fails. I am not trying to do anything with the data...I just want to ensure that the query executes with no problems.
Is there any other information I can give that might help here? This seems really simple to me...yet so confused here as to why this isn't working.
You can see your mysql errors with mysql_error (for the purposes of learning):
if (!$r) {
echo mysqli_error(); // display the last error detected
}
Also using the mysql_* & mysqli_* functions are a very old & insecure way of communicating with mysql. Look into pdo for a better way.

Mysql_error() Not Catching INSERT Error in PHP

new here and really green to programming, so go easy..
I discovered I have an INSERT that is failing because of a duplicate record error. I figured it out by running the query in a MySQL console with literals, where err#1062 popped up.
What I want to understand is why mysql_error() or mysql_errno() didn't catch this error in my PHP script.
Below is a generic setup of what I've done. I have a form that submits to a php file that calls data_insert()
function data_insert($var1, $var2, $var3, $var4){
$db = db_connect();
$query = "INSERT INTO exampletable (id, id_2, id_3, id_4)
VALUES ('$var1', '$var2', '$var3', '$var4')";
$result = $db->query($query);
if (!$result)
{
echo ('Database Error:' . mysql_error());
}
else
{
echo "Data added to db";
}
}
The DB connection:
function db_connect()
{
$result = new MySQLi('localhost', 'root', 'root', 'dbname');
if (!$result)
throw new Exception('Could not connect to database server');
else
return $result;
}
Result I'm getting is:
Database Error:
PHP echos "Database Error:" because the INSERT fails, but no subsequent MySQL error info is echoed. Honestly, I'm not exactly sure what I'm supposed to see, but through reading some other SO questions, I've double-checked my php.ini file for error handling and E_ALL and display_errors is set appropriately (although not sure if it matters in this case).
Is there something in my logic that I'm not understanding, like the scope of the link resource mysql_error() takes?
Thanks for your help, I'm hoping this is something embarrassingly obvious.
I know the above is missing XSS and security precautions and uniform exception handling. Baby steps though. It's simplified here for discussion's sake.
You're using mysqli (note the i) for your DB operations, but are calling mysql_error (no i). They're two completely different interfaces, and do not share internal states at at all. DB handles/results from one are not usable in the other.
Try mysqli_error() instead (note the I).
As far as I can tell, you appear to be using the MySQLi class for connecting and queries, but you're trying to access MySQL error message. MySQLi and MySQL aren't the same, so errors in one will not show in the other. You should look up error handling for MySQLi, not MySQL.
You are confusing two seperate methods for connecting to a mySQL DB.
mysql_error() will only work on queries that are run through mysql_query().
As you are using mysqli, you must use mysqli_error()

Categories