I'm having an issue yesterday and today with my host (godaddy) who apparently is having trouble with a particular mysql server... in that it's completely out of commission for a few hours at a time.
Right now this causes my site to not load at all - showing this error:
[phpBB Debug] PHP Warning: in file /home/content/index.php on line 53: mysqli::mysqli() [mysqli.mysqli]: (HY000/2003): Can't connect to MySQL server on 'dbserver.com' (110)
Connect failed: Can't connect to MySQL server on 'dbserver.com' (110)
I'm guessing it's showing that because of this code I have:
// PREPARE DB CONNECTION
$mysqli = new mysqli("dbserver.com", "username", "password", "dbname");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Which tells the php to stop altogether if mysql is down. So I suppose all I need to do is remove the "exit" function and I'm good to go?
I guess theoretically speaking, why is exit there by default in so many tutorials of how to connect to mysql? It kills the web site if the database is unavailable.
Just looking for thoughts from those who know much more than I please, thank you!
Just bin this:
printf("Connect failed: %s\n", mysqli_connect_error());
And replace it with a placeholder page instead to inform people that s**t happened and you'll be back later.
header('Location: error_db.php');
Displaying good and pretty error-messages to the user is often neglected by most programmers. This is because it can be a real pain in the ass to do the right way.
As Jassica commented, if your entire site function without the database-connection, you can just remove the exit() in your function and the site is good to go.
However, I guess the chances for a 100 % functional site without the database-connection are very small. What most sites to is to redirect the user to a 500-errorpage where they inform the user that something went wrong. Often provided contact-information so the right people can be notified too. Twitter does this, so does Facebook, Reddit and many more.
You can just do:
$mysqli = new mysqli("dbserver.com", "username", "password", "table");
if (mysqli_connect_errno()) {
header("Location: error500.html");
exit();
}
Or something like that.
This should do the trick.
function connect($u,$p,$db,$host) {
try {
$mysqli = new mysqli($host,$u,$p,$db);
$connected = true;
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
try {
connect('username','password','database','host');
} catch (Exception $e) {
echo $e->errorMessage();
}
Related
I have recently deployed my new website, I use GoDaddy Unlimited Hosting and I'am unable to connect to the database for some reason.
Here's my code for connecting my website to the database:
<?php
ob_start();
session_start();
// db properties
define('DBHOST','some.example.ip.Address');
define('DBUSER','username');
define('DBPASS','password');
define('DBNAME','database-name');
$conn = #mysql_connect (DBHOST, DBUSER, DBPASS);
$conn = #mysql_select_db (DBNAME);
if(!$conn) {
die('Some Error Message');
}
define('included', 1);
?>
And Instead of connecting my website to the database and showing the content It shows the die() error message I have used above, And I tried adding if (! $conn) { mysql_error() or die('some message'); } I can see my website but can't see the db content and when I submit any form It shows this message Query failed. Access denied for user 'root'#'localhost' (using password: NO)
Thank you for your time.
Look into using PDO. mysql_connect is deprecated and generally not considered secure. However, it should still work.
Here's a simple PDO connection:
TRY {
$handler = new PDO('mysql:host=localhost;dbname=NameofDB','username','password');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
CATCH(PDOEXCEPTION $e) {
echo $e->getMessage() . "<br>";
die ('sorry for your luck!');
}
There are lots of tutorials around the web for PDO implementation, and it's generally considered he way to go.
I am new to web development, so probably there is something I am doing it wrong.
I am using webmatrix for development and playing around with StarterSite sample that webmatrix provides.
In one of the php file (header.php) there is a query to mysql using mysqli extension. I have changed the tablename to some non existent table to simulate error condition. The problem is, after below statement -
$statement->execute();
the script stops.
I inserted a echo statement after execute and that echo string is not displaying on webpage. However when I correct the table name, the echo string after execute is displayed on webpage. So I think the script stops executing after execute when the table name is wrong. I have two questions. How do I stop script from stop executing like this? Secondly How to know for sure that script has stopped executing at some particular statement?
For second part of question, I checked the log file and tracelog file in IISExpress folder. There is no mention of any error, probably because error happened in MYSQL. However, in my MYSQL folder there is no log file, so not sure how to check mysql log.
If I have missed anything, please let me know.
Regards,
Tushar
You should read about mysqli error handling.
Basic error handling example OOP:
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
Procedural:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
It depends on what you're logging. In the error log you can define what's being logged. I think you can control the strict mode of the error in the php.ini which will automatically throw error into the access_log or error_log or apache log file.
The trick is to use $mysqli->error in every step of the mysqli querying and db connects to ensure you're getting proper error messages in detail whether to debug, improve the code or to do it correctly.
Here is an example of using $mysqli->error in querying the database.
$result = $mysqli->query($query);
if (!$result and $mysqliDebug) {
// the query failed and debugging is enabled
echo "<p>There was an error in query: $query</p>";
echo $mysqli->error; //additional error
}
You can also use a method where you define mysql error to be true in db conn
// define a variable to switch on/off error messages
$mysqliDebug = true;
// connect to your database
// if you use a single database, passing it will simplify your queries
$mysqli = #new mysqli('localhost', 'myuser', 'mypassword', 'mydatabase');
// mysqli->connect_errno will return zero if successful
if ($mysqli->connect_errno) {
echo '<p>There was an error connecting to the database!</p>';
if ($mysqliDebug) {
// mysqli->connect_error returns the latest error message,
// hopefully clarifying the problem
// NOTE: supported as of PHP 5.2.9
echo $mysqli->connect_error;
}
// since there is no database connection your queries will fail,
// quit processing
die();
}
#ref: https://www.daniweb.com/web-development/php/code/434480/using-phpmysqli-with-error-checking
I'm working on a website that has a data base (phpmyadmin) with several articles, what i want to do now is to put all off that on a remote server. I never did this with a website that has mysql, i tried this now and it seens it can't connect with the database ('Database error.'). So i have this code to do the connection:
<?php
try {
$pdo = new PDO ('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
catch (PDOException $e) {
exit('Database error.');
}
?>
It all works at 100% on localhost so i guess what it's missing is just the connection. Do I have to do something on this piece of code? if yes, What is it? and do I have to do anything else? plz explain like i'm a child. Thanks very much
Half of the mysqli functions return false on failure. For trouble shooting when developing this is great, but when released how and should this be used? For example if a user encounters an error the technical info may not be relevant so should everything like it be removed from the final product? Part of me is afraid that if the script where the problem happened is included by another script, that would confuse people and would mess up scalability.
if(!$link)
die('Can\'t connect to MySQL: '.mysql_error());
$db_selected = mysqli_select_db($link, 'Storage1');
if(!$db_selected)
die('Can\'t use Storage1: '.mysql_error());
You should never show these messages to the visitor / user.
Instead you should log the error on the server and display a friendly message to the user to try again / try again later / apologize / etc.
I am facing database connection problem while trying to connect a .php file through wamp server
the error message is something like- "Access denied for the user " # ' localhost' " for database 'aschool'. 'aschool' is my database name.
Mentioning that I've changed my port number of wamp server, I am worried that is it really
for changing port number or anything else.Here is my code.
$con = mysql_connect();
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("aschool", $con);
After this line the error message comes. I've tried parameters "localhost" inside the mysql_connect()
function or more parameters but the result is same.
Thanks in advance anyone gives me any solution
That's because you are using mysql_connectwrong for your use case.
If you check the documentation page it says that you can also a server-path,
something like mysql_connect('localhost:1234', 'username', 'password').
But you shouldn't use mysql_connect.
Use PDO so that you can use parameterized queries.
In code it would go like this:
try
{
$pdo = new \PDO('mysql:dbname=aschool;host=127.0.0.1', 'myUser', 'myPassword');
} catch (PDOException $exception)
{
// Do something with your exception.
// Echo it, dump it, log it, die it.
// Just don't ignore the exceptions!
}