I want to check if accessing mysql is possible or not.
I don't wont to have an error message, only true/false if the connection is ready or not.
I tried to do it with this :
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
if ($appDB->connect_error)
{ $res['code']=FALSE; }
else
{
$appDB -> close();
$res['code']=TRUE;
}
But always a error message will come up - how can i prevent this message from showing ?
"<b>Fatal error</b>: Uncaught exception 'mysqli_sql_exception' with message 'Access denied for user ''
#'localhost' (using password: NO)' in /is/htdocs/...mypath
.php:33
Stack trace:
#0 /is/htdocs...mypath.myfile.php(33): mysqli->mysqli('', ''
, '', '')
#1 {main}
thrown in <b>/is/htdocs/wp1076647_373QG1K1B0/butobo/module/4/code/cms_checkcon.php</b> on line <b>33
</b><br />"
You need to "catch" this fatal exception via a try/catch statement. This allows you to handle the fatal error and then instead of your script crashing due to it, you can output an error message and exit instead :D
PHP Exceptions: http://php.net/manual/en/language.exceptions.php
I hope this helps.
try
{
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
if ($appDB->connect_error)
{ $res['code']=FALSE; }
else
{
$appDB -> close();
$res['code']=TRUE;
}
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
exit;
}
This will change the ERROR to a WARNING, which will not break your script. From there, if you want to hide everything EXCEPT fatal errors, you can use this line of PHP:
error_reporting(E_ERROR);
Error message would display because your PHP is configured to do so. To make it not display, simply configure it like
ini_set('display_errors', "0");
However, this code also stops the execution. It order to prevent it, you have to catch the exception. So it should be like
try {
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
$res['code']=TRUE;
}
catch (Exception $e)
{
error_log($e);
$res['code']=FALSE;
}
while setting error_reporting(E_ERROR); is rather stupid as it will prevent you from seeing all other errors
Related
I am new to php, i am from java background, i am wondering why php doesn't goes directly when exception occured in try block without throwing that exception manually.
e.g.
<?php
//create function with an exception
function checkNum($number) {
if($number/0) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>
in above example in if condition the divide by zero exception is occured and then it will directly go to the catch block instead it goes to inside if.why?
The code you posted doesn't do what you say it does.
When you execute:
if ($number/0)
the division by zero prints a warning, and then returns false. Since the value is not truthy, it doesn't go into the if block, so it doesn't execute the throw statement. The function then returns true. Since the exception wasn't thrown, the statement after the call to checkNum(2) is executed, so it prints the message.
When I run your code, I get the output:
Warning: Division by zero in scriptname.php on line 5
If you see this, the number is 1 or below
PHP doesn't use exceptions for its built-in error checks. It simply displays or logs the error, and if it's a fatal error it stops the script.
This has been changed in PHP 7, though. It now reports errors by throwing an exception of type Error. This isn't a subclass of Exception, so it won't be caught if you use catch (Exception $e), you'll need to use catch (Error $e). See Errors in PHP 7. So in PHP 7 you could write:
<?php
//create function with an exception
function checkNum($number) {
if($number/0) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception in a "try" block
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below';
}
//catch exception
catch(Error $e) {
echo 'Message: ' .$e->getMessage();
}
I have a Database class:
<?php
namespace Database\MySQL;
class Database
{
function __construct(){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$this->Connection = new mysqli(
"", // Testing with no host
"", // Testing with no user
"", // ... no password
"" // and no DB name
);
}
catch (mysqli_sql_exception $e) {
throw $e;
}
...
?>
But instead of a getting an exception, I get a Fatal error: Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'No database selected' in Database.php.
I have tried the same thing with a simple query:
try {
$this->Connection->query("SET NAMES 'utf87'"); //utf87 just for test
}
catch (mysqli_sql_exception $e) {
throw $e;
}
And I still get Fatal error: Uncaught exception.
Your problem is that you are catching the exception, but then just throwing it again without catching it.
If you replace throw $e; with echo "Caught the exception";, you will see that your script is catching the exception. But because you throw it again, it will result in an error unless you have a higher-level try/catch block or a global exception handler.
Also, as many have pointed out in the comments, you need to be careful of namespaces. You need to use a use statement or refer to \mysqli_sql_exception.
i've try this example :
<?php
try {
Not_Exist();
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
http://php.net/manual/en/language.exceptions.php
But the error is not catched :
Fatal error: Call to undefined function Not_Exist() in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\data\localweb\mysite\public_html\exception.php on line 3
Why? I'm usually using Dotnet. Maybe i miss something.
error is not an exception. PHP itself doesn't throw exceptions on syntax errors, such as missing functions. You'd need set_error_handler() to "catch" such things - and even then, a custom error handler can't handle parse errors such as this.
There is no Exception being thrown in your code. You're simply hitting a fatal error. If you're trying to find a way around fatal errors, this post may be of help. How do I catch a PHP Fatal Error
If you're trying to catch Exceptions, something like this:
try {
throw new Exception("Exception Message");
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Because that is a fatal error, not an exception. You're going to want to use PHP's function_exists() method and try something like:
try{
function_exists(Not_Exist);
} catch (Exception $e) {
// error here
}
// run Not_Exist here because we know its a valid function.
When I try to process url http://www.bbc.co.uk/ dompdf throws error
fatal error: Uncaught exception 'DOMPDF_Exception' with message 'Box property calculation requires containing block width' in www\dompdf\include\block_frame_reflower.cls.php on line 171
It seems some settings or some bug?
DOMPDF_Exception is an extension of the Exception class. I'm not sure what parameters it will spit out, but you can dump the array out to see what is being returned:
try{
}catch(DOMPDF_Exception $e){
echo '<pre>',print_r($e),'</pre>';
}
Also found this on Google Code that might help you narrow down, what the actual issue is: http://code.google.com/p/dompdf/issues/detail?id=244
No, you just have to catch exceptions or set your stuff properly.
try {
//Do your stuff here
} catch (Exception $e){
echo $e->message() ;
}
I believe the correct way to return the message is
try {
//Do your stuff here
} catch (Exception $e){
echo $e->getMessage() ;
}
for the first time i came across try, throw catch statement in PHP, and i felt this could be the better way for handling errors as i was quite messing my error handlers with lots of if else statements, however as i am performing CRUD operations on my script i wanted my error handlers to perform two task.
display the user readable or
custom error message back to the
user.
catch all the error in a file for
me to read.
i am using the following code..
try
{
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if($cname == $name)
{
throw new Exception('Sorry, Please Change the value to update ');
}
$sth = $dbh->prepare("UPDATE countries SET name = :name WHERE id = :cid");
$sth->bindParam(':name', $name);
$sth->bindParam(':cid', $cid);
$sth->execute();
}
catch(PDOException $e)
{
echo $e->getMessage();
file_put_contents("resources/logs/Connection-log.txt", DATE.PHP_EOL.$e->getMessage().PHP_EOL.PHP_EOL, FILE_APPEND);
}
if the condition $cname == $name is true i just want to display the error 'Sorry, Please Change the value to update, however this is not happening here, instead it throws the Fatal Error with this message.
Fatal error: Uncaught exception 'Exception' with message 'Sorry, Please Change the value to update ' in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/countries.php:24 Stack trace: #0 /Applications/MAMP/htdocs/kokaris/administrator/location-manager.php(43): include() #1 {main} thrown in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/countries.php on line 24
how do i achieve this?
thank you..
Your catch is catching a PDOException :
catch(PDOException $e)
While you are throwing a Exception :
throw new Exception('Sorry, P...
PDOException is a sub-class of Exception, which means that :
A PDOException is an Exception
But an Exception is not a PDOException.
So, when you are trying to catch a PDOException, your catch will not also catch Exception.
If you want your Exception to be catched, you must use something like this :
try {
}
catch (PDOException $e) {
// deal with PDOException
}
catch (Exception $e) {
// deal with all other kinds of exceptions
}
In this case, the catch PDOException can be avoided, if you do not want to do some special treatment for PDOExceptions, and just want all exceptions to be dealt with the same way :
try {
}
catch (Exception $e) {
// deal with all kinds of exceptions
}
You are throwing an Exception but catching a PDOException.
You should catch the same as you throw, so you might want to change your catch to:
catch(Exception $e)
Or if you also want to catch that PDOException and not do the file_put_contents for your own excpetion, add a catch for your specific Exception.
YOu could ofcourse also change your throw to PDOException, same thing basically.