I am currently using this code to hide mysqli_connect() errors.
error_reporting(E_ALL);
ini_set('display_errors',0);
But with reporting ON, when I introduce an incorrect setting into a mysqli_connect() param the usual gibberish appears. Is it possible to display a message of my own such as "Check DB connection settings" rather than the garble you usually get IF mysqli_connect() fails?
I presume this is done with try/catch. Can anyone shed some light on this with of how I might do the above?
Could be along the lines of pseudo If mysqli_connect bad settings, echo "bad settings please check".
Thanks.
Try this:
mysqli_connect("myhost","myuser","mypassw","mybd") or die("THIS IS THE ECHOED MESSAGE");
You can also use this:
$conn= mysqli_connect("myhost","myuser","mypassw","mybd") or die("SOME PREAMBLE: " . mysqli_error($conn));
Related
What I was trying to do is inserting all query errors into a database, but, it doesnt work. I wanted to do this:
<?php
include('db_settings.php');
$query = $conn->query("mysql_query here");
if (!query) {
$error = $conn->error;
$log_error = $conn->query("INSERT INTO tab (log) VALUES ('$error')");
}
?>
However, this does not work, the error is not being submitted into the db.
Does any of you know some workaround for this?
(before someone asks, all parameters of DB and variables are correct).
You simply shouldn't do that.
Do not try to use a medium that failed you that very instant!
Let's take one of your recent questions: The very error message that troubled you here, Mysqli Commands out of sync will prevent your wunderlogging from functioning! Your database won't get back to sync by magic! And thus will effectively prevent you from logging its own error. And so you simply will never have an idea it occurred.
Let errors to be logged, and then you'll be able find them all.
add these three lines at the top of your code,
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and then check the server error log.
This is how everyone is doing it and there is no reason to devise such an awkward and illogical device.
When I'm connecting to MySQL using the mysqli class constructor I get an echoed error message from PHP when I don't provide the correct connection details. However, there is an appropriate way to deal with errors, like connect_errno and connect_error, but PHP always seems to echo the fact that a connection was unsuccessful whereas I want to deal with any errors manually.
ini_set('display_errors', FALSE);
I think it is a foolish question but I cannot understand why it is happening... I want to connect to my MySQL database with this simple code:
<html>
<head>
<title>File1</title>
</head>
<body>
<?php
$con=mysql_connect("localhost","root","") or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db("Users",$con) or die("Failed to connect to MySQL: " . mysql_error());
if (mysql_error()) {
echo "Failed to connect to MySQL: " . mysql_error();
}
?>
</body>
</html>
As user, I use root. The problem is that root needs a password. So, with this code I should obtain on my screen "Failed to connect to MySQL", right? However, the screen is white.
Why is white instead of appearing "Failed to connect..."?
Many thanks!
I think errors are not displayed in your server , Inside your php.ini add or change value of this line:
display_errors = on
Then restart your web server.
Probably a simple case of fatal errors being hidden?
Use this to turn errors on:
error_reporting(E_ALL);
ini_set('display_errors', true);
In your page, Your connection got established, there is no success message, there is no other browser output aswell. So that it seems blank screen.
if ($con) {
echo "Connection successful!!";
}
The reason you're not getting any output is because of the or die.
die() stops the execution of the script.
$con=mysql_connect("localhost","root","");
$db=mysql_select_db("Users",$con);
The difference between error display on or off, is the warning you get before the script exits through the die() command.
You will always see the message printed by die() at the end of the output as that is unrelated to any php error handling:
Failed to connect to MySQL: Access denied for user 'root'#'localhost'
(using password: NO)
The only reason I can think of that the message not shows, is that the php is not getting executed; for example if your file is an .html file instead of a .php file. That would lead to a blank page as the opening < of the php section will be seen as the opening of an html tag and the same applies to the closing tag.
Checking the source of the output would confirm that.
Your $db variable is unassigned.
Use this instead, by removing $db=
mysql_select_db("Users",$con) or die("Failed to connect to MySQL: " . mysql_error());
Plus, mysql_ functions are deprecated. For more information on this, visit the PHP.net Website.
http://www.php.net/manual/en/function.mysql-db-query.php
I suggest you start using mysqli_ with prepared statements or PDO instead.
WARNING
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
I have some code that allows a user to input details for their database on their server. After they submit the details, the code checks a connection to the database to see if valid details were entered. I want it to give outcomes of variables being true if the connection either works or does, like this:
$mysqli = new mysqli($_POST['dbHost'],$_POST['dbUser'],$_POST['dbPassword'],$_POST['dbName']);
if ($mysqli->connect_errno) { $badDetails = true; }
else { goodDetails = true; }
Problem is, if the details are indeed incorrect, it shows a PHP warning from the first line of the code above giving 'Unknown MySQL server host'.
What is the way around this? I don't want PHP throwing it's own visible error for this, I want to deal with the error myself.
You should not worry about visual errors. In a production environment, these should be turned off in the ini, and all errors should go to a log on the server instead of just to the screen.
This is configured with the display_errors setting and error_reporting()
Many frameworks override the PHP error handler with a custom implementation to display error in a pretty way, depending on their severity.
To achieve this, you can override the PHP error handler
As seen in the manual one can register custom handlers for regular errors and exceptions. And it is also possible to trigger an user defined error.
Just use a die()
$mysqli = new mysqli($_POST['dbHost'],$_POST['dbUser'],$_POST['dbPassword'],$_POST['dbName']) or die("Database Connection Failed");
A quick, dirty method would be error supression:
$con = #mysqli_connect( /* info */ );
Note that you should not keep this there, as this will suppress all errors, and mysqli can have multiple errors that you might need to know about.
Though I would check the host variable first, to see why the error is caused. You can also use die.
$con = mysqli_connect(/* info */) or die ("SQL Error!");
As far as where to look, try seeing that the host var is actually set and check it's value:
if (!isset($_POST['dbHost'])) {
echo "Host var not set!";
} else {
echo "Host var set: " . $_POST['dbHost']
}
How would I go about getting PDO statements to generate a safe error message? I don't want the user to see the error message. I want them to get directed to a page that says a clean message, "Whoops something unexpected happened!". I would also like to log the errors in a database to review and catch errors others are generating.
I'm using PHP and MySQL.
I found that when you make your connection you can set your error handling like this.
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Anyone do anything like this before?
So this is just a suggestion as I have never tried this but after thinking about it a bit I think it would be an interesting option to explore. As I am fairly new to PHP & PDO I'm sure there are other and better ways.
Perhaps you could try using the try function of PHP and then instead of echo'ing (if failed) the PDOException you could run another function that prints it to a text file. Something like.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
$strFileName = 'whatever.txt';
if(!is_writable($strFileName))
die('Change permisions to ' . $strFileName);
$handle = fopen($strFileName, 'a+');
fwrite($handle, "\r" . $e->getMessage() . "\r");
fclose($handle);
}
?>
This way you would avoid a DB connection (which is the problem I guess) but still save the error.
You would perhaps want to omit the echo'd text after die within the if statement.
I think it is better to write your logs to a file, instead of a database. Especially since you want to log PDO errors, which indicate something is wrong with your database connection.
You can show the user a nice error page by catching your errors. You can redirect your users to your error page then, in case something went wrong.
You have to understand that PDO do not generate a "safe" or "unsafe" error message. It does generate an error message. That's all. The rest is is the responsibility of site-wide PHP settings.
PDO is not the only source of errors. Why care of PDO errors only? Why not to handle ALL errors the same way?
Want errors logged? It's a matter of one PHP ini setting.
Want errors not to be displayed? It's a matter of one PHP ini setting.
Want generic error page to be shown? It's a matter of simple function that will handle all errors at once.
Everything can be done proper and straight way, without wrapping every statement into try catch. Without writing into log manually. Without even single additional line of code.
You need to set up PHP error handling, not PDO.
And of course, it makes absolutely no sense in trying to store a database error in the same database that failed you right now. Errors have to go into error log on a live server and on screen - on a local development PC.
Anyone do anything like this before?
Sure. Every single one of 1000000s sites in the world. The way described above.