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));
Related
I am using pdo connection. I am trying to run a delete query but it is showing this message in the browser
*SQLSTATE[HY000]: General error*
Here is my query:
$user_id = $_POST['user_id']; $result = query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
I don't know why happening this. Any kind of help will be appreciated.Thanks
I think there is a query() function does not exists in PHP .. It should be mysql_query or mysqli_query
Using Mysql query is bad because it is depreciated in Updated version of php
$result = mysqli_query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
//So using mysqli :)
$result = mysqli_query($conn, "DELETE FROM user WHERE user_id = '$user_id'");
Per MySQL 5.5.35 source code, sql/sql_prepare.cc:
bool
Reprepare_observer::report_error(THD *thd)
{
/*
This 'error' is purely internal to the server:
- No exception handler is invoked,
- No condition is added in the condition area (warn_list).
The diagnostics area is set to an error status to enforce
that this thread execution stops and returns to the caller,
backtracking all the way to Prepared_statement::execute_loop().
*/
thd->stmt_da->set_error_status(thd, ER_NEED_REPREPARE,
ER(ER_NEED_REPREPARE), "HY000");
m_invalidated= TRUE;
return TRUE;
}
It appears that your error (SQL state HY000) will happen when there is a wrong sequence of prepare/execute statements. Double-check our logic to make sure you are properly using prepared statements, e.g properly fetching all of the results after the call to query() before calling it again.
If you cannot figure it out, isolate the problem to a minimal, complete, and verifiable example (https://stackoverflow.com/help/mcve), and post the code here.
UPDATE:
Does the problem go away (or do you at least get a meaningful error message) if you do
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
prior to the query?
I was checking up how to test for query success, and saw this method:
if($db->query(...)){
//It was successful!
} else {
//Something went wrong
}
But does this only check if the query would run successfully, or does it run the query and then return true/false? I'm assuming it is indeed run, but this brings me to the main question:
Can I test if a query was successful in this way, and at the same time store the result set in a variable, like so?
if ($result = $db->query(...)){
//something
}
Otherwise I'd have to run the same query once inside the if statement and then to store the results in a variable..
But yeah, basically, that's all I'm wondering. Thanks for all friendly help. :)
Functions and methods don't behave differently within a specific context.
If $bd->query() runs the query the behavior won't change if it's in a if statement.
So, yes it does run the query
you could try something like this to test your query
$result = $db->query();
if (is_null($result)) {
var_dump($result);
}
If you are looking to validate a query before running it then you can try preparing it first like this:
$prepare = $db->prepare($sql);
// check if SQL compiled
if($prepare)
{
// execute the SQL
$execute = $prepare->execute();
}
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
}
How do I see what is returned from a sql statement in php? I have the following function to get user name from mysql database and I use echo in another php to see the result but nothing shown.
function get_user_name($id_user) {
return mysql_result(mysql_query("SELECT username FROM user WHERE id_user = '$id_user'"));
}
echo $id_user;
$a = get_user_name($id_user);
echo $a;
Can anyone help? Thanks.
Are you echoing the get_user_name(); function?? OR are you even connected to your database? these are two things you need to check before, (if the problem remains) including an error handling method i.e. or die(mysql_error()) at the end of your query to find out the problem.
return mysql_result(mysql_query("SELECT id_user FROM user WHERE id_user = '$id_user'")or die (mysql_error()));
The error handling construct?? in mysql mysql_error() should output the problem in fairly understandable way, as to what is preventing your query not to be shown
When having an error in SQL syntax in classic PHP mysql, the query will not take place without any other effect. But in mysqli, it will kill the PHP script with Fatal error
mysql_query("SELECT title, misspelled_column FROM posts");
$mysqli->query("SELECT title, misspelled_column FROM posts");
In the first case, it will show the other queries and php output; but the second case kills the script by
Fatal error: Call to a member function fetch_assoc() on a non-object
The problem is related to non-object returned by false query. I can skip this error by
if($result){$row = $result->fetch_assoc();}
but my question is that why I did not need this check in classic mysql? With a more advanced system, one expects new features not missing what we had.
An error generated by MySQL should not be stopping execution. In fact, you can have your script show you any SQL errors by using $mysqli->error (assuming $mysqli is your database connection, like in your example). However, what may be happening is that your mysqli error causes a particular object not to be created, and then calling a method on that object will create a fatal PHP error. For example:
$dbconn = new mysqli("localhost", $username, $password, $dbname);
$stmt = $dbconn->prepare("bluh"); // not a valid statement. fails to create a mysqli statement object in $stmt.
echo($dbconn->error); // your script is still running, and this will show your MySQL syntax error.
$stmt->execute();
This will die not because you made an SQL error, but because $stmt was null and didn't have the expected execute() method. So like everyone else has said, check your logs and see what the actual error is.
Using # to ignore errors is going to be hit-or-miss until you figure out which specific command is creating the error.
update: If you know that the error is in the query, then you could check to see whether the query succeeded before you try to do anything with it. One way is to check the error parameter; another is to check to make sure that it actually returned the kind of object you want.
Here are examples of both:
$result = $db->query("select firstname, lastname from people where firstname = 'egbert';");
if($db->error == '') {
// the query worked, so fetch results from $result and do stuff with them.
}
else {
// the query didn't work, so don't try to do anything with $result
}
// alternately:
if(gettype($result) == "object") {
// the query worked.
}
else {
// it didn't.
}
A SQL error doesn't kill mysqli in my experience. I suspect you actually have a PHP error in the relevant statement. Check your error log.
In PHP, you can use # to suppress errors. It's a bad idea to use it here. But if that's what you really want, it's documented at http://php.net/manual/en/language.operators.errorcontrol.php.