check pdo php insert success - php

$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";
}

Related

PHP MYSQL: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

I am searching already 2 days for the error but i cant find out what's wrong. I hope that somebody can help me here.
$query = "INSERT INTO Patient ( patients_ID, height, nameOfTheFamilyDoctor,
nameOfTheHealthInsurance, weight, birthDate, station, room ) VALUES
( :patient, :height, :nameOfTheFamilyDoctor,
:nameOfTheHealthInsurance, :weight, :birthDate, :station, :room) ";
//Again, we need to update our tokens with the actual data:
if (ctype_digit($_POST['height']) && ctype_digit($_POST['weight'])) {
$query_params = array(
':patient' => $_POST['patientsID'],
':height' => $_POST['height'],
':nameOfTheFamilyDoctor' => $_POST['nameOfTheFamilyDoctor'],
':nameOfTheHealthInsurance' => $_POST['nameOfTheHealthInsurance'],
':weight' => $_POST['weight'],
':birthDate' => $_POST['birthDate'],
':station' => $_POST['station'],
':room' => $_POST['room'],
);
}
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
} catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!" . $ex->getMessage();;
die(json_encode($response));
}
I am getting this error message:
{"success":0,"message":"Database Error2. Please Try Again!SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens"}`
I have checked all variables for spelling errors, etc.
Thanks for all you help.
$_POST['height'] and $_POST['weight'] is going to be a string. Try using is_numeric instead of ctype_digit. You can convert to an integer via intval if necessary.
var_dump($query_params) before your try/catch block... see if it even exists outside of your if() statement. You will see that it's null.
Lastly, you need to rethink your logic... what happens if your if() statement fails? Does it make sense to continue the query? In that case, your try/catch should be in if() statement... Then, you should create an else to handle errors. (alternatively, you could throw an error and have an error handler elsewhere).

INSERT command is not being executed? [duplicate]

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());

PDO errorinfo not returns info

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.

How to debug correctly an Insert statement with PDO (mysql)?

$PDO_db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=UTF-8' , DB_USER, DB_PWD);
$sth = $PDO_db->prepare($insert);
$arrPar = array(':nome' => $nome);
$r = $sth->execute($arrPar);
var_dump($arrPar);
print_r($PDO_db->errorInfo());
var_dump($r);
exit();
Supppose that the $insert statemet contains a SQL error, with the code above I've noticed the following :
Code A
print_r($PDO_db->errorInfo());
will output anyways:
Array (
[0] => 00000
[1] =>
[2] =>
)
but var_dump($s) is false
If in the insert statement I have some placemark e.g. :name
"Insert into mytable (name) VALUE(:name);"
And then in the $arrPar = array(':name' => $value) with $value=NULL
print_r($PDO_db->errorInfo());
will output again:
Array
(
[0] => 00000
[1] =>
[2] =>
)
but var_dump($s) is false
So I'm wondering to know what's the correct way to debug MySQL statements with PDO if the method errorInfo, which is supposed to give me a error description, silently quiets errors?
PDO::errorInfo() returns an array of error information"
Strange... are you sure nothing is being iserted? MySQL's return code on success is 0, which the errorInfo does return. But like #Jack said:
try
{
$PDO_db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=UTF-8' , DB_USER, DB_PWD);
$PDO_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $PDO_db->prepare($insert);
echo 'Insert prepared<br/>';
$arrPar = array(':nome' => $nome);//shouldn't this be :name?
$r = $sth->execute($arrPar);
echo 'Insert executed<br/>';
var_dump($r);
}
catch(PDOException $pdoE)
{
echo $pdoE->getMessage().'<br/>';
var_dump($pdoE);
}
exit();//?
That should give you more clues as to what is going on. Also, you state (twice) that a var_dump of $s is false, but you're assigning the return value of the execute call to $r... I'm assuming that's a typo, but you never know, hence the comment on ':nome'.Also take #Clarence's advice to heart, and set your php.ini error reporting to E_ALL | E_STRICT, you might hate the vast amount of warnings it issues at first, but it avoids any issues you might (and probably will) encounter when you deploy your code on another machine, or you upgrade your PHP version. Anyway: it's not like PHP is that strict of a language that E_STRICT is going to cost you huuuge amounts of time to fix the warnings...

PDO error message? [duplicate]

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());

Categories