I am working with PDO in PHP.
Now I wonder if you could catch any global error and show.
With global I mean if any $sql=$connect->prepare() fails, then echo out
"Something went wrong:" . the_error
Or would you need to always do it invidually each $sql ?
You can do it using PDO::errorInfo()
http://www.php.net/manual/en/pdo.errorinfo.php
That's about as global as youre going to get.
You could always catch exceptions thrown by the PDO class.
try
{
...new PDO('odbc:SAMPLE', 'db2inst1',...
}
catch(PDOException $exception)
{
echo "Failed: " . $exception->getMessage();
}
Related
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.
I'm using PHP and PDO. Now I want to build a kind of log when things go wrong. What can go wrong with PDO?
Right now I have these tests:
Connection test
try {
$this->pdo = new PDO($dsn, $credentials['user'], $credentials['pass'], $options);
} catch(Exception $e) {
$this->file->put( date('Y-m-d') . '.txt', 'log', 'Database error');
}
Execute test
try {
$stmt->execute();
} catch(Exception $e) {
$this->error->log('SQL', 'query error');
}
Any more tests that are good?
You do not log your exception message in your logs. I suggest you to do something like this into your catch :
$this->error->log('SQL', $e . PHP_EOL);
This will give you more understandable and readable logs.
Regarding the exceptions to catch with PDO, you may read that post : How to handle PDO exceptions
I am trying to implement transactions to Kohana but it seems to be not so easy as in Spring/Java.
So far I found this code to try but I don't know how to replace the part (no errors)
DB::query('START TRANSACTION');
// sql queries with query builder..
if (no errors)
DB::query('COMMIT');
else
DB::query('ROLLBACK');
How do I make the if clause?
Normally transactions are handled as such:
DB::query('START TRANSACTION');
try {
//do something
DB::query('COMMIT');
} catch (Exception $e) {
DB::query('ROLLBACK');
}
What this means is if everything succeeds within the try block, great. If any part of it fails then it won't reach the commit and will jump to the catch block, which contains the rollback. You can add more error handling within the catch if you wish, even throw a new exception of your own or throw the same exception you caught.
Just wrap everything in a try/catch block:
DB::query('START TRANSACTION');
try {
// sql queries with query builder..
DB::query('COMMIT');
} catch (Database_Exception $e) {
DB::query('ROLLBACK');
}
DB errors are converted to exceptions:
DB::query('START TRANSACTION');
try {
// sql queries with query builder..
DB::query('COMMIT');
}
catch($e)
{
$this->template->body = new View('db_error');
$this->template->body->error = 'An error occurred ...';
DB::query('ROLLBACK');
}
If you're using Kohana 3:
$db = Database::instance();
$db->begin();
try
{
// Do your queries here
$db->commit();
}
catch (Database_Exception $e)
{
$db->rollback();
}
I am trying to migrate a PHP app from MySQL to SQLite, and some things that used to work, simply stopped working now. I am using PDO through a custom database wrapper class (the class is a singleton, seems logical to do it like that).
The problem:
When trying to execute a query on a prepared statement, it throws a "fatal error: Call to a member function execute() on a non-object ...".
Relevant code (narrowed it down to this, after some hours of var_dumps and try-catch):
Connection string:
$this->connection = new PDO("sqlite:"._ROOT."/Storage/_sqlite/satori.sdb");
Obviously, the $connection variable here is a private variable from the class.
The error happens here (inside a function that is supposed to perform database insert):
try{
$statement = self::getInstance()->connection->prepare($sql);
}catch (PDOException $e){
print $e->getMessage;
}
try{
var_dump($statement);
$statement->execute($input);
}catch (Exception $e){
print $e->getMessage();
}
More accurately, it happens when I try to $statement->execute($input).
Any help appreciated. Thanks.
You are probably getting a mySQL error when the statement is being prepared, but you don't have PDO configured to throw an exception in case of an error.
<?php
$dbh = new PDO( /* your connection string */ );
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// . . .
?>
try declaring the $statement variable outside the first try block. e.g.
$statement = null;
try{
$statement = self::getInstance()->connection->prepare($sql);
}catch (PDOException $e){
print $e->getMessage;
}
try{
var_dump($statement);
$statement->execute($input);
}catch (Exception $e){
print $e->getMessage();
}
I am a strong Python programmer, but not quite there when it comes to PHP. I need to try something, and if that doesn't work out, do something else.
This is what it would look like in Python:
try:
print "stuf"
except:
print "something else"
What would this be in PHP?
http://php.net/manual/en/language.exceptions.php
try {
print 'stuff';
} catch (Exception $e) {
var_dump($e);
}
Note: this only works for exceptions, not errors.
See http://www.php.net/manual/en/function.set-error-handler.php for that.
try {
// do stuff ...
} catch (Exception $e) {
print($e->getMessage());
}
See http://php.net/manual/en/language.exceptions.php
PHP does not natively support error catching like Python does, unless you override the default behavior and set your own error handler. PHP's try - catch was only recently added to the language in version 5, and it can only catch exceptions you explicitly throw.
So basically, PHP distinguishes between errors and exceptions. Errors haven't been modularized and made available to the user like they have been in Python. I believe that's related to the fact that PHP began as a collection of dynamic web scripts, grew and gained more features over time, and only more recently offered improved OOP support (i.e., version 5); whereas Python fundamentally supports OOP and other meta-functionality. And exception handling from the beginning.
Here's an example usage (again, a throw is necessary, or else nothing will be caught):
function oops($a)
{
if (!$a) {
throw new Exception('empty variable');
}
return "oops, $a";
}
try {
print oops($b);
} catch (Exception $e) {
print "Error occurred: " . $e->getMessage();
}
You can handle PHP errors like they were exceptions by using set_error_handler
In this error handler function you can throw various exception, according to error level for instance.
By doing this you can treat any error (including programming errors) in a common way.
PHP 5 has the exception model:
try {
print 'stuff';
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Assuming you're trying to catch exceptions, take a look at http://php.net/manual/en/language.exceptions.php
You could try something like
try {
echo "Stuff";
} catch (Exception $e) {
echo "Something Else";
}