PHP / MySQL General Error - php

I got a trigger that executes when I update the table, everything works fine trigger executes great however I get a return in PHP in catch statement telling me General Error. I am not sure what is wrong wondering if anyone here can catch it.
Here is the code
$sql = "UPDATE pre_reg SET active =:val WHERE authentication =:auth";
try{
$query = $this->pdo->prepare($sql);
$query->bindParam(':val', $val, PDO::PARAM_INT);
$query->bindParam(':auth', $auth, PDO::PARAM_STR);
$query->execute();
$user = $query->fetch();
if($user){
return 'Congratulation you have activated your account!';
}else{return '';}
}catch (PDOException $e){
return 'This error:' .$e->getMessage(); // Store to file
}
ERROR
SQLSTATE[HY000]: General error
In the above code I always get catch return, even though in my database everything seems to happen according to the $sql / followed by a trigger.
I am open to suggestion thanks!

Comment out
$user = $query->fetch();
As you cant use fetch methods when inserting or udating the data.

Related

PHP PDO output user-defined Exceptions

I've got a (example) Oracle Stored Procedure:
CREATE OR REPLACE FUNCTION EXCEPTION_TEST
RETURN NUMBER
AS
BEGIN
raise_application_error(-20500, 'This is the exception text I want to print.');
END;
and I call it in PHP with PDO with the following code:
$statement = $conn->prepare('SELECT exception_test() FROM dual');
$statement->execute();
The call of the function works perfectly fine, but now I want to print the Exception text only.
I read somewhere, that you should not use try and catch with PDO. How can I do this?
You have read that you shouldn't catch an error to report it.
However, if you want to handle it somehow, it's all right to catch it.
Based on the example from my article on handling exception in PDO,
try {
$statement = $conn->prepare('SELECT exception_test() FROM dual');
$statement->execute();
} catch (PDOException $e) {
if ($e->getCode() == 20500 ) {
echo $e->getmessage();
} else {
throw $e;
}
}
Here you are either getting your particular error or re-throwing the exception back to make it handled the usual way
You check the execute response and get the error, for example, like this:
if ($statement->execute() != true) {
echo $statement->errorCode();
echo $statement->errorInfo();
}
You can find more options at the PDO manual.

PDO Transactions. What is the right way to roll back [duplicate]

I'm pretty new to transactions.
Before, what I was doing was something like:
Code Block 1
$db = new PDO(...);
$stmt = $db->prepare(...);
if($stmt->execute()){
// success
return true;
}else{
// failed
return false;
}
But in an attempt to group multiple queries into a single transaction, I'm now using something like:
Code Block 2
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
try{
$stmt = $db->prepare(... 1 ...);
$stmt->execute();
$stmt = $db->prepare(... 2 ...);
$stmt->execute();
$stmt = $db->prepare(... 3 ...);
$stmt->execute();
$db->commit();
return true;
}catch(Exception $e){
// Failed, maybe write the error to a txt file or something
$db->rollBack();
return false;
}
My question is: If the transaction fails for whatever reason, does the code stop at $db->commit(); and jump to the catch block? Or would the return true; run first, and then it would try to go to the catch? 'Cause if that's the case, then I've already returned, and so it wouldn't go to the catch. AND it would have returned the wrong value.
Do I still need to include something like:
Code Block 3
if($stmt->commit()){
return true;
}
or is it sufficient the way I have it written in Code Block 2?
If the transaction fails for whatever reason, the code does stop at the very line where error occurred end then the execution jumps directly to the catch block. So it is sufficient the way you have it written in Code Block 2.
Note that you should always re-throw the Exception after rollback. Otherwise you will never have an idea what was a problem. So it should be
try{
$stmt = $db->prepare(... 1 ...);
$stmt->execute();
$stmt = $db->prepare(... 2 ...);
$stmt->execute();
$stmt = $db->prepare(... 3 ...);
$stmt->execute();
$db->commit();
return true;
}catch(Exception $e){
$db->rollBack();
throw $e;
}
The execution is stopped when an exception is thrown.
The first return will not be reached but the catch statement will be executed.
You can even return the commit directly:
$dbh->beginTransaction();
try {
// insert/update query
return $dbh->commit();
} catch (PDOException $e) {
$dbh->rollBack();
return false;
}
if you face any error you can do this to rollback all transactions like this
catch(Exception $e){
$db->rollBack();
// Failed, maybe write the error to a txt file or something
return false;
}

ZF2: How to get error info from Zend\Db

I am connecting to MySQL through PDO with Zend\Db from ZF2. How can I report the last errorInfo()?
Here's what I have:
$sqlWriter = new Sql($this->getAdapter());
$insert = $sqlWriter->insert('table_name')->columns(array_keys($data))->values($data);
$stmt = $sqlWriter->prepareStatementForSqlObject($insert);
try {
$stmt->execute();
$object->id = $this->getAdapter()->driver->getLastGeneratedValue();
} catch (\Exception $e) {
//
// HOW CAN I display errorInfo() here?
//
throw new Exception\Exception('Unable to insert record...');
}
I have tried calling methods on the adapter, driver, statement, platform, result, etc... But all to no avail...
EDIT: I found that I can get the info I am looking for by posting the following at the top of the catch block:
$pdoException = $e->getPrevious();
var_dump($pdoException);
I'll leave the question open however since it would be good to know how to execute PDO::errorInfo() directly.

MySQL query works but PHP returning Exception: errorinfo:null

The following code updates the table correctly, but it also returns an Exception. Any idea what might be happening here?
public function updateThis($aaa){
try
{
$success = false;
$query = "
UPDATE this_table
SET thing = '0'
WHERE aaa = :aaa";
$stmt = $this->conn->prepare($query);
$stmt->bindParam(':aaa', $aaa);
$stmt->execute();
if($this->conn->commit())
$success = true;
return $success;
}
catch(Exception $e)
{
return $e;
}
}
When you are using PDO, Auto-Commit is on by default, unless you specifically turn it off using Begin Transaction. I can't see it in your connection, so are you perhaps trying to commit a transaction that has already been auto-commited?

Fatal error: Call to a member function prepare() on a non-object PDO PHP Class

So I'm writing a PHP class called article and it has a bunch of methods like insert, delete and update. I have 3 other functions that follow the same code and they all work so I don't know why I am getting this error. Here is the code I wrote.
public function update(){
//make sure that the article does have an I.D
if(is_null($this->id)) trigger_error("Article::update(): Attempt to update an Article object that does not have its ID property set.", E_USER_ERROR );
//If there are any PDO errors they will be caught.
try{
$connection1 = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$connection1->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$sqlQuery = "UPDATE articles SET lastEditDate=FROM_UNIXTIME(:lastEditDate), lastEditUser=:lastEditUser, title=:title, content=:content WHERE id = :id";
$statement->prepare($sqlQuery);
$statement->bindValue(":lastEditDate", $this->lastEditDate, PDO::PARAM_INT);
$statement->bindValue(":lastEditUser", $this->lastEditUser, PDO::PARAM_STR);
$statement->bindValue(":title", $this->title, PDO::PARAM_STR);
$statement->bindValue(":content", $this->content, PDO::PARAM_STR);
$statement->bindValue(":id", $this->id, PDO::PARAM_INT);
$statement->execute();
$connection1 = null;
}
catch(PDOException $e){
echo "update():I'm sorry, Dave. I'm afraid I can't do that.";
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
}
}
I read that you can get it from previous queries so I tried renaming and setting a bunch of the variables to null. I also checked the other threads I could find from this site and other and almost all of them were scope issues, which I don't think is the problem here since all my other functions work. Is there something painfully obvious that I'm missing?
It should be $connection1->prepare(), not $statement->prepare().

Categories