Difference between mysql_errno and mysql_error - php

Can anybody explain the difference between mysql_errno and mysql_error?

mysql_errno returns the error code, while mysql_error returns the error text...

Are you saying the functions of php ?
mysql_errno returns the number of the error,
and mysql_error returns the text of the error.
You can easily find the difference in http://www.php.net/manual/en/function.mysql-errno.php

string mysql_error ([ resource $link_identifier ] )
Returns the error text from the last MySQL function. Errors coming back from the MySQL database backend no longer issue warnings. Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.
mysql_errno is the number of the error

mysql_error — Returns the text of the error message from previous MySQL operation
mysql_errno — Returns the numerical value of the error message from previous MySQL operation

I would add to the topic that MySQL-specific error numbers returned by mysql_errno() are not the SQL error numbers you could expect, they differ from SQLSTATE values (returned by mysql_sqlstate() or sqlstate property inside a mysqli_sql_exception). You can find a complete list of error messages and error numbers for your MySQL distribution here (in addition to the Docs/mysqld_error.txt file).
Source: MySQL Reference Manual

Related

PHP mysqli DB connection: error messages

I am testing the die () clause in the below code. When I enter an incorrect password and use the mysqli_connect_error() function, everything works as expected and I get the MySQL error message. Why does it not work when I use mysqli_error()? I was under the impression mysqli_error() should return the last error description, regardless of error type, for the most recent function call? Im using PHP 5.2.17
This works:
$conn = mysqli_connect("localhost","testUser","incorrectPassword","testDB")
or die(mysqli_connect_error());
This does not work:
$conn = mysqli_connect("localhost","testUser","incorrectPassword","testDB")
or die(mysqli_error());
Would like to understand why.
It needs the connection mysqli_error($link).
The mysqli_error() function is identical to the corresponding mysqli_errno() function in every way, except instead of returning an integer error code the mysqli_error() function will return a string representation of the last error to occur for the database connection represented by the link parameter. If no error has occured, this function will return an empty string.
http://php.net/manual/en/mysqli.error.php
One is for the connection the other 2 for query errors.

PDO SQL-state "00000" but still error? [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
Can anybody explain why
$sql->execute($params);
returns FALSE, whereas
print $pdo->errorCode();
print_r($pdo->errorInfo());
both return SQLSTATE 00000, which means according to the documentation success? It is an INSERT and nothing is actually being inserted into the database... so, why do I get a success message from SQLSTATE?
In case it helps, this is the code...
$sql = $pdo->prepare("
INSERT INTO user (
username, fname, pass, salt, email,
loc_id_home, country_id_home, region_id_home,
cont_id_home, timestamp_reg, timestamp_upd, timestamp_lastonline,
online_status, gender, birthdate
)
VALUES (
:username,:fname,:pass,:random_salt,:email,
:loc_id_home,:country_id_home,:region_id_home,
:cont_id_home,'".time()."','".time()."','".time()."',
1,:gender,:birthdate)
");
$params=array(
':username'=>$username,
':fname'=>$fname,
':pass'=>$pass,
':random_salt'=>$random_salt,
':email'=>$email,
':loc_id_home'=>$loc_id_home,
':country_id_home'=>$country,
':region_id_home'=>$region,
':cont_id_home'=>$continent,
':gender'=>$gender,
':birthdate'=>$birthdate
);
$sql->execute($params);
print $pdo->errorCode();
print_r($pdo->errorInfo());
It is because $pdo->errorInfo() refers to the last statement that was successfully executed. Since $sql->execute() returns false, then it cannot refer to that statement (either to nothing or to the query before).
As to why $sql->execute() returns false, I don't know... either there is a problem with your $params array or with your database connection.
PDO::errorCode — Fetch the SQLSTATE associated with the last operation on the database handle
Note: The PHP manual (http://php.net/manual/en/pdo.errorinfo.php) does not define exactly what "last operation on the database handle" means, but if there was an issue with binding parameters, that error would have occurred inside PDO and without any interaction with the database. It is safe to say that if $pdo->execute() returns true, that $pdo->errorInfo() is valid. If $pdo->execute() returns false, the behavior of $pdo->errorInfo() is not explicitly clear from the documentation. If I recall correctly from my experience, execute returns true, even if MySQL returned an error, returns false if no operation was done. Since the documentation is not specific, it might be db driver specific.
This answer reflects practical experience as of when it was written in September 2012. As a user has pointed out, the documentation does not explicitly reaffirm this interpretation. It also may only reflect the particular database driver implementation, but it should always be true that if $pdo->execute() returns true, that $pdo->errorInfo() is valid.
You might also want to set PDO::ERRMODE_EXCEPTION in your connect sequence. Exception handling makes it unnecessary to check and query the error.
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
I Faced the similar problem ,
This occurs manly due to error in query, try to run your query in php-myadmin or any other query runner and confirm that your query is working fine.Even if our query syntax is correct other simple errors like leaving null or not mentioan a column that set as not null in table structure will cause this error.(This was the errror made by me)
As user1122069 explained the reason for $pdo->errorInfo() says nothing is wrong may be due to
$pdo->errorInfo() refers to the last statement that was successfully
executed. Since $sql->execute() returns false, then it cannot refer to
that statement (either to nothing or to the query before)
Hopes this helps :)
From the php manual:
PDO::ERR_NONE (string)
Corresponds to SQLSTATE '00000', meaning that the SQL statement was successfully issued with no errors or warnings. This constant is for your convenience when checking PDO::errorCode() or PDOStatement::errorCode() to determine if an error occurred. You will usually know if this is the case by examining the return code from the method that raised the error condition anyway.
So it sounds like it did insert the record. Check the last record id in your table... maybe you just missed it?
I was getting this error at one time. I only got it on one server for all failures. A different server would report the error correctly for the same errors. That led me to believe it was a MySQL client configuration error. I never solved the specific error, but check your configurations.
Try to check $sql by print_r() and copy your query then try resultant query in phpMyadmin. Hope will get the reason. There would be chance of irrelevant value.

Get an array in php mysql error like oci_error

Since some time ago I have been programming in php with oracle, and I've always liked the function oci_error() because the function can give me the byte position of the error in the query (offset) and then I can make a function to show the error with a flag indicating where is the error in the query.
Well I'm making a similar function but with mysql:
I have the mysql_error() which gives me the "message".
I have the mysql_errno() which gives me the "code".
The "sqltext" I can get it with the function itself.
But, How can I get the offset value of the error in the query?
MySQL errors are usually of the type
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near...
Following the "near" keyword is the part of the query where the error occurred. You could search for this string using strpos() in your query and use that as the offset.

if mysql_query() fails, what to do?

Sometimes so happens that mysql_query() fails to INSERT data and I am unaware of it. So, the question is how do I know when it happens?
Quoting the documentation page of mysql_query :
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.
For other type of SQL statements,
INSERT, UPDATE, DELETE, DROP, etc,
mysql_query() returns TRUE on
success or FALSE on error.
So, to detect whether there's been an error or not, you have to test the return value of your call to mysql_query :
$result = mysql_query('...');
if ($result === false) {
// And error has occured while executing
// the SQL query
}
Then, what can you do ?
Well, first, you can log the error to a file, that you can analyse later
For than, you can use mysql_error and mysql_errno.
And you can display a nice error message the user
i.e. some kind of "oops, an error occured page".
Remember, though : the user doesn't need to know (and will not understand) the technical error message -- so don't display it.
You can use mysql_error php.net/mysql_error to get a better explanation that you then either display or log it in a file.
One check that I usually do is like in the example
$result = mysql_query( $query );
if ( !empty( $error = mysql_error() ) )
{
echo 'Mysql error '. $error ."<br />\n";
}
else
{
// the query ran successfully
}
This is a good check for any kind of queries
suggest making a wrapper for mysql_query that detects failure and logs the query plus mysql_error somewhere
If you're using a sensible client library, it will throw an exception when a SQL command fails, and you can examine the error code programmatically to know what to do.
If you have no code handling that specific error path, you should probably run a standard error handler which logs the error, stack trace and some other debug info into a log.
you have to analyze your sql. did you escape your parameters? sounds like this could be the problem. you may paste your sql so we can help you.
for showing the error, you can eg.
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
.
If the cause of the error is deadlock, you might want to try again.
You can check how many rows MySQL has inserted/updated/deleted by doing this query right after your insert/update/delete query.
SELECT ROW_COUNT() as rows_affected
If this returns 0 your insert failed. If it returns 1 or more you've succeeded.
See: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_row-count
Probably you can check LAST_INSERT_ID() (mysql_insert_id() in PHP). Provided that your table has auto_increment column.

mysql query occasionally returns nothing

We have a function used within our PHP/MySQL application which returns basic configuration information, it contains a simple select query and looks like this:
public function getConfigurationValue($field)
{
$res = mysql_query("SELECT `cfg_value` FROM `ls_config` WHERE `cfg_name` = '".mysql_real_escape_string($field)."'");
$cfg = htmlspecialchars(mysql_result($res,0));
return $cfg;
}
This problem we are having is that occasionally, seemingly at random, this query throws a mysql error on mysql_result saying that "supplied argument is not a valid mysql result resource". In our debugging we have determined though that this is not because $field is not being passed. Essentially, for a reason we cannot determine a perfectly valid query fails and returns no results causing an empty result set and the subsequent error. If the error was due to the mysql connection failing the script would have died well before this. Also, this function may be called 50-100 times on some page loads but it only tends to fail once on each load.
Please let me know if you need any other information to work this out.
Thanks.
searching for php "supplied argument is not a valid mysql result resource" reveals that to get the actual error, you'd need to call mysql_error, and the error that you get is because the result of the query is FALSE - this value not being a valid mysql result resource.
i.e. in short you have something like:
$res = FALSE; # should contain the mysql result but does not, due to error.
$cfg = htmlspecialchars(mysql_result($res,0)); # the attempt to call mysql_result on invalid argument errors out.
So you'd want to use something like this:
$query = "SELECT * FROM cats WHERE id=$id";
$qr1 = mysql_query ($query)
or die ("Query failed: " . mysql_error() . " Actual query: " . $query);
You might want to give this a shot and see what the underlying error message says.
Given that the error is "MySQL server has gone away", There can be multitude of reasons for it - this article would be a good start to investigate. Searching suggests also some php-related and stack-specific bugs, so it looks like you might need to debug it with a closer attention.
Maybe try to duplicate the setup on another box and then start experimenting with the versions/settings, and see if any of the already reported scenarios match your case. Unfortunately, seems there's no single simple answer to this.

Categories