zend framework 2 how catching exceptions? - exception

How I can catch exception in zend framework 2 using the PHP base Exception?
If line is uncommented then Exception class not found and exception is uncatched.
If line is commented the namespace is null and PHP base Exception class is founded.
I can't uncommented this line because is required by zend in many places, i.g. ActionController.
How do it?
Have I to use only Zend Exceptions?
which I have to use and what is the more generic zend Exception class?
<?php namespace SecureDraw; ?> // <<----- If remove this line catch work ok!!
<?php echo $this->doctype(); ?>
<?php
use Zend\Db\Adapter\Adapter as DbAdapter;
try{
$dbAdapter = new DbAdapter(array(
'driver' => 'Pdo_Mysql',
'database' => 'securedraw',
'username' => 'root',
'password' => '',
));
$sql = "select * from tablenotexist";
$statement = $dbAdapter->createStatement($sql);
$sqlResult = $statement->execute();
}
catch(Exception $e){
echo "hello";
}
?>

You need to either add:
use Exception;
or use:
catch (\Exception $e) {
All the built in PHP classes exist within the root (\) namespace. The try-catch in your example is trying to match SecureDraw\Exception.
This is the same issue as How to catch exceptions in your ZF2 controllers?

Related

Executing a bad PDO query does not yield an error [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
Here is an invalid SQL and I m expecting an error, but the PDO error seems always 00000, what did I do wrong?
<?php
run('select now()');
run('pls give me an error');
function run($sql) {
$pdo = new PDO('mysql:host=localhost;db=mydb', $user, $pass);
echo $sql . "<br>";
$sth = $pdo->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
print_r($row);
print_r($pdo->errorInfo());
}
And here is the result:
select now()
Array
(
[now()] => 2017-10-03 02:58:09
)
Array
(
[0] => 00000
[1] =>
[2] =>
)
pls give me an error
Array
(
[0] => 00000
[1] =>
[2] =>
)
But I have another page running against the same db and get this error:
Err 1064: 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
'please give me an error' at line 1
updated
The other page is able to produce error is actually using the following:
$sth = $pdo->query($sql);
print_r($pdo->errorInfo());
For the syntactically or any other way incorrect prepared statements to throw you need to disable prepared statements emulation:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
By default PDO is set up to emulate those, which honestly does not make much sense.
With emulated prepares disabled PDO::prepare() method creates a temporary server-side object that holds a prepared statement then executes it.
Additionally you may want to enable PDO exceptions, that way it's harder to not handle unexpected query failures:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
References:
http://php.net/manual/en/pdo.setattribute.php
I've no idea why errorInfo() sometimes doesn't work but I confirm he behavior.
Given that setting error mode to exceptions always works and given that exceptions are much more useful than manual error checking, this function is useless anyway.
So, change your function this way
function run($pdo, $sql, $params = null) {
$sth = $pdo->prepare($sql);
$sth->execute($params);
return $stmt;
}
$pdo = new PDO('mysql:host=localhost;db=mydb', $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
run($pdo, 'select now()');
run($pdo, 'pls give me an error');
and have your error message first class

How to check if query returned true or false in replacement for mysql_error() in PDO

I am creating a web based application, and I am using PDO for my database. I have a query that selects everything from login table where username=something and password=something.
My code:
$query = $db->prepare("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindParam(':username',$username);
$query->bindParam(':password',$password);
$query->execute();
However I want to check if the query returned true or false. For example in mysql we used to say:
$query = mysql_query("SELECT * FROM login WHERE username='$username' AND password='$password' ");
if($query == false){
die(mysql_error());
}
My question is, how do I check if the query returned false or true using PDO and gives an error? This will help me get errors on my code during development.
What am I going to replace the mysql_error() with?
We set PDO in exception mode.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
We wrap queries with try/catch block. If an Exception is thrown, we catch it. That's the equivalent of using if(!mysql_query($query)) echo mysql_error();
Your example would be
try
{
$query = $db->prepare("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindParam(':username',$username);
$query->bindParam(':password',$password);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo "Whoopsie, an error occurred! Message: ". $e->getMessage();
}

Exception handling issue in zend framework 2

try {
Zend_Loader::loadClass('nonexistantclass');
} catch (Zend_Exception $e) {
echo "Caught exception: " . get_class($e) . "\n";
echo "Message: " . $e->getMessage() . "\n";
}
I'm using your above code for zend framework 2 in some controller action method , after executing some line its getting blank , It seems that exception has been caused but why the its not displaying $e->getMessage() content . Do i need to use any name space for using this , or what is the correct way to use Exception Handling in zend framework 2 . Please help me
Just trying to provide a sample code.
It should be -
try {
$model = new NonExistantClass(); //Any code that will throw an Exception.
} catch (\Exception $e) {
echo "Message: " . $e->getMessage();
}
The \ backslash before the Exception $e states that the Class is not under the namespace mentioned at the top of the page but its the core PHP class.

MySQL query runs without error but does not populate database

Evening folks,
Having another of those "looked at this too long moments".
This code when run return the success message but nothing gets entered into the database table, no errors being thrown up, I know all the correct values are being received from _post but I can't see what's wrong, I have an almost identical query on another page and it works fine.
Can anyone see issues with the code?
if (isset($_POST['username']) && $_POST['username'] !== '')
{
$salted = md5($_POST['pass1'] . 'salt');
try
{
$sql = 'INSERT INTO users SET
username = :username,
firstname = :firstname,
lastname = :lastname,
email = :email,
password = $salted,
joined = CURDATE()';
$s = $PDO->prepare($sql);
$s -> bindValue(':username', $_POST['username']);
$s -> bindValue(':firstname', $_POST['firstname']);
$s -> bindValue(':lastname', $_POST['lastname']);
$s -> bindValue(':email', $_POST['email']);
$s -> execute();
}
catch (PDOException $e)
{
$error = 'Error adding submitted user.';
echo $error;
exit();
}
?> <div class="alert alert-success">User added to the database.</div> <?php
}
Summarizing comments here, for the sake of having an answer. Marked Community Wiki.
A string in your INSERT statement should be quoted.
password = '$salted',
You should use a parameter anyway.
password = :password,
. . .
$s -> bindValue(':password', $salted);
MD5 isn't the preferred hashing function for modern strong password storage. Neither is SHA1.
Try to use SHA256 or Bcrypt instead.
$salted = hash('sha256', $_POST['pass1'] . 'salt');
Salting is better if you use a random salt string per user.
Make sure your PDO instance is configured to throw exceptions.
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Always capture the PDO exception's error message, even if you don't output it to users.
error_log($e->getMessage());

Perl web service : Using XML RPC

Something is wrong with this code.
#!/use/bin/perl
use strict;
use warnings;
use Frontier::Daemon;
use DBI;
sub credentials {
my ($username, $password) = #_;
my $tablename = "users";
my $user = "db_user";
my $pw = "db_pass";
$dbh = DBI->connect('DBI:mysql:database;host=localhost', $user, $pw, {RaiseError => 1});
$sql = "SELECT username, password FROM $tablename";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
if ($sth->rows > 0) {
$login_response = "Login Successful";
} else {
$login_response = "Invalid Credentials";
return {'login' => $login_response};
die();
}
}
$methods = {'login.credentials' => \&credentials,};
Frontier::Daemon->new(LocalPort => 8080, methods => $methods)
or die "Couldn't start HTTP server: $!";
This is another problem with your code - you're not doing anything with the supplied username and password. You need to add a where clause to your SQL statement, so:
my $sql = 'SELECT * FROM users WHERE username = ? AND password = ? ';
my $sth = $dbh->prepare($sql);
$sth->execute($username, $password);
However, given that your example is selecting all records from the 'users' table, I'd have thought that credentials() would at least be returning some rows. However, I'm afraid that I've not used Frontier::Daemon in the past, so I'm not able to help on that front.
I also can't see how this code would work given that you are using strictures. $dbh, $sql, $sth and $login_response haven't been declared. So make sure that you're using 'my' in the right places - as per my example above.
To fix the problems you mentioned with returning the correct string - the logic in your if statement isn't quite right. You are returning the string 'Login Successful' when there's a successful login and the hashref { login => $login_response } when no user could be found.
I think the confusion arose from the layout of the braces. I must stress that you try and indent you code properly, which will make it much more readable to yourself and other developers when debugging and maintaining the code in the future.
The following logic should do the job.
if($sth->rows > 0){
return "Login Successful";
}
return "Invalid Credentials";