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.
Related
I have code as below where I am redirecting the user at the end but sometimes it seems that the output variable is not getting set or insert query is not getting executed . So is there any way I can wait for all the operations to be completed before the die statement is executed.
Thanks
$diff=levenshtein(strtolower($str1),strtolower($str2));
if($diff<=2)
{
$output="ok";
}
else
{
$output="Not ok";
}
$query="INSERT INTO `table` (`sn`, `output`) VALUES (NULL,'$output')";
$result=mysqli_query($con,$query);
header('Location: http://www.domain.com/');
die;
There may be several reasons why it doesn't work.
The first one and most obvious is that is enough to have only one simple warning on your page (variable X is not set) and this will broke your header() command. It would say that headers have been already set.
The second problem is that sometimes the server is so busy answering other request and your $con variable will be a Boolean false instead of a reliable database connector, therefore your query could fail because of this too.
I encountered both situations in real life and I solved them by ensuring that every variable is set before use it and by checking if the query was executed successfully.
You can check if a variable is set by using this code:
if (!isset($variable)) $variable = "set me here";
You can check if your query was succesfully executed by adding this:
if (!$result) {
//do something here in case your query failed
}
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.
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.
I'm a beginner programmer, and I've installed XAMPP with the intention of learning a bit of PHP. I have a working knowledge of SQL.
I've been following the PHP tutorial at w3schools. The problem I am currently having is this: I'm using the script here to create a database and a table within it. What I'm using is almost verbatim, except I've replaced the user with "root" and I've deleted the password.
After running the script through the browser, the database my_db appears in the datafile for mysql in XAMPP.
However, there is no sign of a table, and when I try to select the table, I get
Table 'my_db.persons' doesn't exist
What is going on? Is there something wrong with the code I took verbatim, or is it something with permissions?
It's weird that the database is created but not a table...
What has happenned is that your "CREATE TABLE" will have failed.
Get into the habit of checking for errors after EVERY mySQL query (in your code): there are some times you can ignore errors, but it's rare. So program alonghte lines of:
Create query: $sql =
Set parameters: $aParams = (or bind paramters)
Execute query
If errors
If debug: Show error and query
If live: Log error and query
I'm not giving the solution is code, as one problem with the tutorial you follow is that it uses mysql_() functions that are going to be depreciated shortly. You should use PDO (PHP Database Objects) or mysqli() functions otherwise your code will not work in a few releases time.
With PDO, you can set error handling to use exceptions, and you wrap every call in try {} catch {} and this makes the habit of catching and reporting errors very easy.
$sql = 'CREATE TABLE....';
$aParams = array(
':param_name' => $param_value,
':param_name2' => $param_value2
);
try {
$stmnt = $db->prepare($sql);
$stmnt->execute($aParams);
$stmnt = null;
} catch (Exception $e) {
// Error log here; $e contins line of error and the actual error, you have $sql and $aParams
LogDBError($e, $sql, $aParams);
}
I created a debug function to email me the mysql error and query executed if a query is not successful.
I call it like this:
mysql_query($sql) or $this->debug->dbErrors($sql);
And the function is:
function dbErrors($sql = ''){
if($this->doDebug)
echo mysql_error()."<br/>".$sql;
else
#mail(hidden_email,$_SERVER['HTTP_HOST'].' Mysql Error','A error occured in '.$_SERVER['HTTP_HOST'].':<br/>'.mysql_error().'<br/>'.$sql);
}
The problem is that i'm receiving emails even when the query executes fine (at least the data is inserted and everything works out ok)
What i doing anything wrong?
Thanks
That 'or' construct may be causing issue, I would do something like:
$result = mysql_query($sql);
if (!$result) {
$this->debug->dbErrors($sql);
}
This way you are doing an explicit check to see if $result is a boolean false (query is invalid), or a resource (query is valid). The point is to only call on $this->debug->dbErrors() if there indeed is an issue, otherwise the way your code is written, every query will be emailed.
or something simple like:
mysql_query($sql) or die(dbErrors($sql));