I have code:
$stmt = $db->prepare(" bla bla ");
$stmt->execute();
print_r($db->errorInfo());
This returns: Array ( [0] => 00000 [1] => [2] => )
Why not returned error info ?
The following reports the error correctly:
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
if (($stmt = $dbh->prepare(" bla bla ")) === false) {
print_r($dbh->errorInfo());
}
if ($stmt->execute() === false) {
print_r($stmt->errorInfo());
}
Note in the above that parse errors caused during prepare() are reported against $dbh. Whereas even if the prepare() succeeds, then execute() may cause an error, but that error is reported against $stmt.
In the test above, I got the error report immediately after the prepare():
Array
(
[0] => 42000
[1] => 1064
[2] => 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 'bla bla' at line 1
)
But this behavior changes if you use emulated prepares.
When you enable that attribute, the prepare() is virtually a no-op. It just saves the query string in the $stmt, and then the actual prepare of the statement is delayed until you call execute(). So the error, if any, is reported against $stmt whether it happens at prepare time or at execute time.
I tested changing the error-reporting line as follows:
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
// prepare won't report SQL errors, it's virtually a no-op.
if (($stmt = $dbh->prepare(" bla bla ")) === false) {
print_r($dbh->errorInfo());
}
// execute will report errors of parsing or execution.
if ($stmt->execute() === false) {
print_r($stmt->errorInfo());
}
In this case, no error was reported at prepare(), and but I got the same error as above at execute(). Again, you must examine $stmt to get the error after execute().
SQLSTATE 00000 means "Success". Per the PHP documentation:
If the SQLSTATE error code is not set or there is no driver-specific error, the elements following element 0 will be set to NULL.
Related
I m running PHP 7.2.16
Not sure when started, PDO errorCode() or errorInfo()[0] now always shows 00000 even there is an error
$pdo = new \PDO('mysql:host=localhost;dbname=mydb', 'root', 'pwd');
$sth = $pdo->prepare('select now() and this is a bad SQL where a - b from c');
$sth->execute();
$row = $sth->fetchAll();
$err = $sth->errorInfo();
echo $sth->errorCode();
print_r($row);
print_r($err);
And here is the result:
00000Array
(
)
Array
(
[0] => 00000
[1] => 1064
[2] => You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'a bad SQL where a - b from c' at line 1
)
However, I just did a new test, by delete $sth->fetchAll() or get error before this line, it shows correctly:
Array
(
[0] => 42000
[1] => 1064
[2] => You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'a bad SQL where a - b from c' at line 1
)
OK - the solution is that:
get the error code immediately after execute() and before any fetch
I tested this code with PHP 7.1.23:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
$sth = $pdo->prepare('select now() and this is a bad SQL where a - b from c');
if ($sth === false) {
echo "error on prepare()\n";
print_r($pdo->errorInfo());
}
if ($sth->execute() === false) {
echo "error on execute()\n";
print_r($sth->errorInfo());
}
Output:
error on execute()
Array
(
[0] => 42000
[1] => 1064
[2] => 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 'a bad SQL where a - b from c' at line 1
)
Then I tested the same code, except after disabling emulated prepare:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Output:
error on prepare()
Array
(
[0] => 42000
[1] => 1064
[2] => 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 'a bad SQL where a - b from c' at line 1
)
Fatal error: Uncaught Error: Call to a member function execute() on boolean
Moral of the story:
When using emulated prepared statements, prepare() is a no-op, and the error is delayed until execute(). I recommend disabling emulated prepare, unless you use a database that doesn't support prepared statements (I don't know of any current version of any RDBMS product that can't do real prepared statements).
When checking for an error on prepare(), use $pdo->errorInfo().
When checking for an error on execute(), use $stmt->errorInfo().
$hpaystmt = $con->_con->prepare(".....");
object(PDOStatement)#7 (1) { ["queryString"]=> string(1515) " INSERT INTO hpay ( enccode, orno, hpercode, acctno, amt, curcode, paytype, paycode, entryby, payctr, chrgcode, itemcode, chrgtbl) VALUES ( '000060000000000101783710/14/201722:00:00', '00000000033', '000000001017837', '2017-000165903', '1500', 'PESO', 'F', 'C', '', '1', 'DR', 'DR1', 'MISC') "}====object(PDOStatement)#8 (1) { ["queryString"]=> string(1517) " INSERT INTO hpay ( enccode, orno, hpercode, acctno, amt, curcode, paytype, paycode, entryby, payctr, chrgcode, itemcode, chrgtbl) VALUES ( '000060000000000101783710/14/201722:00:00', '00000000033', '000000001017837', '2017-000165903', '100', 'PESO', 'F', 'C', '', '2', 'BIRTC', '085', 'MISC') "}
I get the above code when from
ini_set('display_errors', 1);
var_dump($hpaystmt);
$hpayinsert = $hpaystmt->execute();
echo "==";
echo $hpaystmt->execute() === TRUE ;
echo "==";
My aim is to check if the insert is success or not but echo $hpaystmt->execute() === TRUE ; this line always return blank that is why i alwats get
}==== in echo;
I dont get any error from display error and also I wrap this in try catch and I always go in try part not catch.
How can I check this for success insert?
OTHER INFO:
I want to check if success so that if it fails I want to rollback the database my var $hpayinsert is set to $hpayinsert = true; before the inserting. then after i check for true or false then commit or rollback depending on the value of that var.
UPDATE:
after putting print_r($hpaystmt->errorInfo()); I get:
Array( [0] => 22001 [1] => 8152 [2] => [Microsoft][ODBC SQL Server Driver][SQL Server]String or binary data would be truncated. (SQLExecute[8152] at ext\pdo_odbc\odbc_stmt.c:254) [3] => 22001)Array( [0] => 22001 [1] => 8152 [2] => [Microsoft][ODBC SQL Server Driver][SQL Server]String or binary data would be truncated. (SQLExecute[8152] at ext\pdo_odbc\odbc_stmt.c:254) [3] => 22001)
You don't need it.
There are three possible scenarios for handling the result of insert operation in PDO:
To tell the success, no verification is needed. Just keep with your program flow.
To handle an unexpected error, keep with the same - no immediate handling code is needed. An exception will be thrown in case of a database error, and it will bubble up to the site-wide error handler that eventually will result in a common 500 error page.
To handle an expected error, like a duplicate primary key, and if you have a certain scenario to handle this very error - then use a try..catch operator.
For a regular PHP user it sounds a bit alien - how's that, not to verify the direct result of the operation? - but this is how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.
So, in a generic case you don't need any handling code at all. Just keep your code as is.
I wrote an article on PHP error reporting basics explaining the matter in detail, you may find it useful
Only in case you have a handling scenario other than just reporting the error, you could catch an error. To rollback a transaction for example. The code is taken from my PDO tutorial:
try {
$pdo->beginTransaction();
$stmt = $pdo->prepare("INSERT INTO users (name) VALUES (?)");
foreach (['Joe','Ben'] as $name)
{
$stmt->execute([$name]);
}
$pdo->commit();
}catch (Exception $e){
$pdo->rollback();
throw $e;
}
Maybe with a try catch
ini_set('display_errors', 1);
var_dump($hpaystmt);
try{
$hpaystmt->execute();
echo "It's a success";
}
catch(Exception $e)
{
echo "Something went wrong";
}
Hi can anyone help me on this
$stmt = $conn->prepare("update data set anrede=?, vorname=?, nachname=?, strasse=?, plz=?, ort=?, krankenkasse=?, seit=?, personen=?, telefon=?, termin=?, time=?, vermittler=?, coment=?,feedback=?, Astatus=?, positiv=?, personen_amgaben=?, fr_1=?, fr_2=?, z_fr_2=?, fr_3=?, z_fr_3=?, fr_4=?, z_fr_4=?, fr_5=?, fr_6=? where t_id=?");
$stmt->bind_param('sssssssssssssssssssssssssssi',$anrede, $vorname, $nachname, $strasse, $plz, $ort, $krankenkasse, $seit, $personen, $telefon, $termin, $time, $vermittler, $coment, $feedback, $Astatus, $positiv, $personen_amgaben, $fr_1, $fr_2, $z_fr_2, $fr_3, $z_fr_3, $fr_4, $z_fr_4, $fr_5, $fr_6, $t_id);
I got this error --- Fatal error: Call to a member function bind_param() on a non-object in
what's wrong
The error indicates that $stmt is not an object. This can happen when $conn->prepare() fails. As from the documentation:
mysqli_prepare() returns a statement object or FALSE if an error occurred.
So, you should check whether the return value is false, and then check what the error is, which you can do with the mysqli error method:
Returns the last error message for the most recent MySQLi function call that can succeed or fail.
So your code could look like this:
stmt = $conn->prepare(" ... ");
if (stmt === false) {
die($conn->error);
}
$stmt->bind_param( ... );
Note that in production mode you better not print database error messages to the browser, but in a log file.
From comments it appears that the above code prints:
Unknown column 'positiv' in 'field list'
which is a clear indication of why the statement failed. Your table data apparently has no column that is called positiv. So correct that typo (maybe it is called positive?), and then try again, fixing any other errors that might be reported in this way.
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
Here is a snippet of my code:
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
$sth->execute($data);
print_r($this->pdo->errorInfo());
This should give me an error because the tables don't even exist. All I get however is this:
Array ( [0] => 00000 )
How can I get a better description of the error so I can debug the issue?
Try this instead:
print_r($sth->errorInfo());
Add this before your prepare:
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.
Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:
$field1 = 'foo';
$field2 = 'bar';
$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);
$insert_QUERY->execute();
$databaseErrors = $insert_QUERY->errorInfo();
if( !empty($databaseErrors) ){
$errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
$errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...
/*
$errorLogMsg will return something like:
error info:
Array(
[0] => 42000
[1] => 1064
[2] => 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 'table bogus(field1, field2) VALUES ('bar', NULL)' at line 1
)
*/
} else {
# no SQL errors.
}
Maybe this post is too old but it may help as a suggestion for someone looking around on this :
Instead of using:
print_r($this->pdo->errorInfo());
Use PHP implode() function:
echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.
Hope it helps
From the manual:
If the database server successfully
prepares the statement, PDO::prepare()
returns a PDOStatement object. If the
database server cannot successfully
prepare the statement, PDO::prepare()
returns FALSE or emits PDOException
(depending on error handling).
The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
Here is a snippet of my code:
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
$sth->execute($data);
print_r($this->pdo->errorInfo());
This should give me an error because the tables don't even exist. All I get however is this:
Array ( [0] => 00000 )
How can I get a better description of the error so I can debug the issue?
Try this instead:
print_r($sth->errorInfo());
Add this before your prepare:
$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
This will change the PDO error reporting type and cause it to emit a warning whenever there is a PDO error. It should help you track it down, although your errorInfo should have bet set.
Old thread, but maybe my answer will help someone. I resolved by executing the query first, then setting an errors variable, then checking if that errors variable array is empty. see simplified example:
$field1 = 'foo';
$field2 = 'bar';
$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);
$insert_QUERY->execute();
$databaseErrors = $insert_QUERY->errorInfo();
if( !empty($databaseErrors) ){
$errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
$errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...
/*
$errorLogMsg will return something like:
error info:
Array(
[0] => 42000
[1] => 1064
[2] => 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 'table bogus(field1, field2) VALUES ('bar', NULL)' at line 1
)
*/
} else {
# no SQL errors.
}
Maybe this post is too old but it may help as a suggestion for someone looking around on this :
Instead of using:
print_r($this->pdo->errorInfo());
Use PHP implode() function:
echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.
Hope it helps
From the manual:
If the database server successfully
prepares the statement, PDO::prepare()
returns a PDOStatement object. If the
database server cannot successfully
prepare the statement, PDO::prepare()
returns FALSE or emits PDOException
(depending on error handling).
The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.
$qry = '
INSERT INTO non-existant-table (id, score)
SELECT id, 40
FROM another-non-existant-table
WHERE description LIKE "%:search_string%"
AND available = "yes"
ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());