PHP error while I'm trying to test my failsafe error message - php

I am trying to test a failsafe for a school project, code works on my teacher's PC but doesn't work for me at home, he told me it could be a bug from my side. Here's the code I'm trying to use:
<?php
// Connexion à la bdd
$hote = "localhost";
$nom_utilisateur = "root";
$mot_de_passe = "";
$bdd_nom = "pwd_kla_tp2";
$bdd = mysqli_connect($hote, $nom_utilisateur, $mot_de_passe, $bdd_nom);
// Erreur bdd
if(!$bdd){
echo "<h1>Connexion échouée à la base de donnée</h1>";
echo "<h2 style='color: darkred;'>Message d'erreur:</h2>";
echo "<h3>".mysqli_connect_error()."</h3>";
exit();
}
Basically, I'm changing the database to a wrong name, so it should display the failsafe messages, but instead here's the message I get in the browser :
Fatal error: Uncaught mysqli_sql_exception: Unknown database 'pwd_kla_tp2' in C:\xampp\htdocs\pwd\pwd_kla_tp2\includes\bdd.php:8 Stack trace: #0 C:\xampp\htdocs\pwd\pwd_kla_tp2\includes\bdd.php(8): mysqli_connect('localhost', 'root', Object(SensitiveParameterValue), 'pwd_kla_tp2') #1 C:\xampp\htdocs\pwd\pwd_kla_tp2\models\site.model.php(3): require('C:\xampp\htdocs...') #2 C:\xampp\htdocs\pwd\pwd_kla_tp2\controllers\site.controller.php(3): require('C:\xampp\htdocs...') #3 C:\xampp\htdocs\pwd\pwd_kla_tp2\index.php(3): require('C:\xampp\htdocs...') #4 {main} thrown in C:\xampp\htdocs\pwd\pwd_kla_tp2\includes\bdd.php on line 8
I'm using xampp and as I said earlier, it's working for my teacher, so clearly there is something I have to fix at home.
Thank you!
I changed the database name to test my fail safe, I was expecting the echoes to display.

Probably due to different environment variables. Based on the documentation for mysqli_connect:
If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.
Try disabling exceptions using
mysqli_report(MYSQLI_REPORT_ALL ^ MYSQLI_REPORT_STRICT);

Related

Code stops its execution when access to database was denied, instead of handling the error [duplicate]

This question already has an answer here:
Why cannot the PHP hide the error message thrown by the MySQL connection?
(1 answer)
Closed last month.
I'm trying to perform a connection between PHP and a MySQL database via Mysqli. I have the following code:
<?php
$database_host = "localhost";
$database_username = "root";
$database_password = "";
$database_name = "test3";
$connection = new mysqli ($database_host, $database_username, $database_password, $database_name);
if ($connection->connect_errno) {
echo ("Can't connect to database because $connection->connect_error"); }
else {
echo ("Connection was successful"); }
?>
I'm using this code for a setup wizard for the users to install a software in their webservers. The point is that if the credentials are correct it prints "Connection was successful", but if wrong its output is:
**Fatal error**: Uncaught mysqli_sql_exception: Access denied for user 'root'#'localhost' (using password: YES) in /opt/lampp/htdocs/uuid/index.php:55
Stack trace:
#0 /opt/lampp/htdocs/uuid/index.php(55): mysqli->__construct('localhost', 'root', '', 'test3')
#1 {main}
thrown in **/opt/lampp/htdocs/uuid/index.php** on line **55**
I currently have error reporting for PHP on (without it, I couldn't get this error message), but regular users who upload the software to a web hosting and they input incorrect credentials will receive a blank page instead.
So how can I print "Can't connect to database because [...]", so users know why is this error being thrown?
In PHP 8.1.0, MySQLi sets the report mode to MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT by default. This causes MySQLi errors to throw exceptions.
So catch the exception and report the error how you want:
try {
$connection = new mysqli ($database_host, $database_username, $database_password, $database_name);
} catch (mysqli_sql_exception $e) {
echo "Can't connect to database because $e";
... return appropriate http status code ...
}
echo "Connection was successful";
Note: The above is just a quick example of handling an exception. Error handling and reporting is a more complex topic, and this is not meant to show the best practice for every application case.

mysql failed connection statement is not working

I'm trying to check the connection with MySQL databse using the following code:
<?php
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','ts');
$link = mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
if($link === false){
header('Location: dberror.php');
}else {
echo "connected successfully";
}
?>
When I try to give incorrect information to test the statement if the connection is not established like giving an incorrect database name, the header is not working and shows the following error:
Fatal error: Uncaught mysqli_sql_exception: Unknown database 'ts' in C:\xampp\htdocs\tst\dbcon.php:8 Stack trace: #0 C:\xampp\htdocs\tst\dbcon.php(8): mysqli_connect('localhost', 'root', '', 'ts') #1 {main} thrown in C:\xampp\htdocs\tst\dbcon.php on line 8
But when the connection is established the else statement is working.
So please how to make a user redirection if the connection failed?
Return values for mysqli_connect() are an object or false. It only returns false if the connection fails. Try var_dump the result of mysqli_connect() to see if you're getting an object. Remember the database field is optional because it can be selected later using mysqli_select_db(), so even if that's empty you will still get an object.
Once the connection is made you can see errors using mysqli_error().

PHP PDOException not catching

I need some guidance on PDO error handling.
I got this code:
<?php
$config = include('config.php');
try{
$handler = new PDO('mysql:host-127.0.0.1;dbname=not_a_valid_dbname', $config->username, $config->password);
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Yup!';
}catch(PDOException $e){
echo 'Caught! '.$e->getMessage();
}
As you can see I provided an unvalid db name. This page outputs 'Yup!' instead of letting me know that there is no such database. Same goes when changing 'mysql:not_valid_host'. Only when I change driver name it throws an error letting me know that there is no driver by that name.
I tried:
Checking php.ini for settigs (I have hard time getting around with this)
Adding
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
Adding
ini_set('display_errors',true);
Also tried adding a backslash in catch param:
catch(\PDOException $e)
Still the same result. Help me break my code :D
The documentation is very unclear, but I've made some tests and drawn some conclusions. This is pure speculation. I'll try to back some of these claims up if I find further information.
If host is not present, localhost is then assumed.
Database name is not mandatory. This is, I imagine, so you can connect to a server and create a new database through PDO.
If you have a syntax error, the string will stop being considered thereafter.
With those suppositions, we can assume why your code is working the way it is. Your DSN is:
mysql:host-127.0.0.1;dbname=not_a_valid_dbname
Since there's a syntax error (- after host), neither of the parameters are considered, and there's no DB selected, with the host being localhost. This is why you get no errors. If you delete the host parameter, however:
mysql:dbname=not_a_valid_dbname
localhost is used as host (selected by default), but not_a_valid_dbname is tried as the database, which results in
Caught! SQLSTATE[HY000] [1049] Unknown database '1234'
mysql:not_valid_host would be the same case as the first example. The DSN is invalid so localhost is assumed with no database selected.
Further, you get no error because no actual DB is selected but you didn't try to run a query. As soon as you do,
try {
$handler = new PDO('mysql:', "root", "root");
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handler->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$handler->query("SELECT * FROM test");
echo 'Yup!';
} catch(PDOException $e) {
echo 'Caught! '.$e->getMessage();
}
You'll get an PDOException, as expected:
Caught! SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
Like I said, all of this is speculation as I couldn't really find concrete evidence on most of this. I hope this guides you in the right direction. I'll keep looking for more information and edit if I find anything.

PHP PDO: Unable to connect, Invalid catalog name

I am trying to set up a new site on my hosting (Host route if it matters) but i keep getting this error when i try using PDO (first PDO site im trying):
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in /home/kennyi81/public_html/gamersite/login.php:36 Stack trace: #0 /home/kennyi81/public_html/gamersite/login.php(36): PDOStatement->execute() #1 {main} thrown in /home/kennyi81/public_html/gamersite/login.php on line 36
When i use these settings:
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
....
$stmt = $dbh->prepare('SELECT * FROM USERS WHERE ID = :id LIMIT 1');
How the database is laid out:
I am able to use mysqli connect fine on my other sub domains / main site, but i just cannot get PDO to work.
I've tried this, which i have seen around:
$stmt = $dbh->prepare('SELECT * FROM gamersite.USERS WHERE ID = :id LIMIT 1');
but it retuns a syntax error.
Anyone have any idea what may be causing this?
This is all working on my local server, nothing changed on upload apart from connect line.
Instead of:
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
Try:
$dbh = new PDO("mysql:host=91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
(add host=)
And it most likely works on your local server, because you have mysql:localhost... or mysql:127.0.0.1... there and it's ignored (cause it's missing host= aswell) and by default it's localhost.
From the PDO manual page, you can see that you need to wrap the connection in a try/catch block. This way if something goes wrong with the connection, it will tell you. Something like this:
try {
$dbh = new PDO("mysql:91.146.107.11;dbname=kennyi81_gamersite", "kennyi81_gamer", "***************");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
// Then actually do something about the error
logError($e->getMessage(), __FILE__, __LINE__);
emailErrorToAdmin($e->getMessage(), __FILE__, __LINE__);
// etc.
die(); // Comment this out if you want the script to continue execution
}
The reason you are getting this error is because there is an error with your connection, but since you don't tell your script to stop, it doesn't. Look at the error message produced, and how to fix it should be made obvious. It appears that Michael Prajsnar's answer is correct in that you aren't setting a "host".
Edit:
As it turns out, PDO doesn't complain if you leave out your host or dbname in the PDO connection DSN part (at least on Unix). I tested it and leaving it blank will default it to "localhost" and I was therefore able to connect perfectly fine leaving this out completely for localhost connections, which would explain why it worked on your local server but not on your production server. In fact, it is completely possible to connect supplying absolutely nothing in the DSN except for the database engine like this:
$dbh = new PDO("mysql:", "kennyi81_gamer", "***************");
The only problem is that it won't be using a database, so to USE a database, just do:
if ($dbh->query("USE kennyi81_gamersite") === false)) {
// Handle the error
}
However with that said, I have my doubts that you actually tried connecting using a try/catch block (as you mention in your comments) unless you somehow provided valid database credentials. The ONLY way that doing it this way did not produce any sort of error is if you actually connected correctly and selected the database kennyi81_gamersite. If not, you would have seen a message like this:
Unable to connect to database. "mysql" said: SQLSTATE[28000] [1045]
Access denied for user 'kennyi81_gamer'#'localhost' (using password: YES)
In summary, always wrap your connection in a try/catch block if you want to find errors during connection. Just make sure not to re-throw (and not catch) the PDOException's getMessage() or you could expose your login credentials.

JQGrid and Microsoft SQL Server

I am trying to get this awesome JQuery plugin working with SQL Server. I have setup PDO as I use it elsewhere (with MS Access) - I think I have it setup with sql server (2008) now. Here is how I connect:
define('DB_DSN',"odbc:Driver={SQL Server};Server=MyInstance;Database=table1;");
define('DB_USER', '');
define('DB_PASSWORD', '');
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
$tsql = 'SELECT * FROM Trt';
// Write the SQL Query
$grid->SelectCommand = $tsql;
// set the ouput format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('report-creator.php');
// Set grid caption using the option caption
$grid->setGridOptions(array(
"caption"=>"Report",
"rowNum"=>10,
"sortname"=>"OrderID",
"hoverrows"=>true,
"rowList"=>array(10,20,50),
));
$grid->toolbarfilter = true;
$grid->setFilterOptions(array("stringResult"=>true));
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
I get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[IM001]: Driver
does not support this function: driver doesn't support meta data' in
C:\wamp\www\webs\tgd\edh\php\jqGridPdo.php(1) : eval()'d code:1 Stack trace: #0
C:\wamp\www\webs\tgd\edh\php\jqGridPdo.php(1) : eval()'d code(1): PDOStatement-
>getColumnMeta(0) #1 C:\wamp\www\webs\tgd\edh\php\jqGrid.php(1) : eval()'d code(7):
jqGridDB->getColumnMeta(0, Object(PDOStatement)) #2 C:\wamp\www\webs\tgd\Front- End\report-
creator.php(31): jqGridRender->setColModel() #3 C:\wamp\www\webs\tgd\Front- End\view-
report.php(123): require_once('C:\wamp\www\web...') #4 {main} thrown in
C:\wamp\www\webs\tgd\edh\php\jqGridPdo.php(1) : eval()'d code on line 1
I appreciate any help - I just can't understand the problem. I have narrowed it down to this function: $grid->SelectCommand - if I remove this no error occurs but I can not do without this as this is where my t-sql to query the database goes.
I am able to query SQL server mysql using PDQ->Query('SELECT * FROM table1').
Thanks all
Please note: I have edited table name, file paths for privacy. :)
Looks like jqGrid uses getColumnMeta function to enumerate columns, but this function may be unsupported by several drivers - in this case, your MSSQL driver.
See examples in the link above to test if getColumnMeta works.
I work for Trirand (the company that developers jqGrid - ASP.NET team) and unfortunately cannot help with PHP much, but I can suggest posting the very same question in our own forums as well:
http://www.trirand.net/forum/
there you will find a PHP jqGrid forum and you will get a timely response from our PHP team. Meanwhile I will write them an email and ask them to help here as well, but just in case posting there will guarantee you an answer.
Cheers,
Rumen Stankov
Trirand Inc
I couldn't solve this so I switched over to another class which was written by the JQGrid guys that makes use of the PHP driver from Microsoft. This solved my problem, hope it helps someone.

Categories