Kaveh
Kaveh

Reputation: 2650

How can I redirect user to 404 page when database fail or when I want disconnect db permanently?

I want disconnect one of my databases as permanently and for connection to this db I use these codes:

$conn = mysql_pconnect($dbhost, $dbuser, $dbpass) or die ('Error connecting to database,please refresh your page.'); 
mysql_select_db($dbname);

Please let me know how can I do it best for this scenario (disconnecting db permanently) and when user comes from search engines redirect it to 404 page.

Upvotes: 1

Views: 374

Answers (3)

Soufiane Lamnizeh
Soufiane Lamnizeh

Reputation: 434

I suggest to redirect the user to another page 404 on using the code bellow:

mysql_pconnect("localhost","root","","db_name")or die(header('Location: URL/404.php'));

Upvotes: 1

François Huppé
François Huppé

Reputation: 2116

You cannot close persistent mysql connection, which is what you have in your connection script (mysql_pconnect). At least you can't close it from PHP. Only way is to restart the mysql server. You need something like this from cmd:

sudo service mysql restart 

Now after having restarted mysql, your persistent connection will be disconnected. If your goal is to disconnect it permanently, now you just need to make sure your connection script never runs again.

About the 404 redirection, you could use this at the top of your script:

header("HTTP/1.0 404 Not Found");

If you wish to send the user to a custom 404 page, you can use:

header("HTTP/1.0 404 Not Found");
include_once("404.html");
exit();

*note: with mysqli, if you are using PHP 7, there seems to be a way to clean persistent connection from PHP, see:

https://www.php.net/manual/en/mysqli.persistconns.php

Upvotes: 0

Mohit Kumar
Mohit Kumar

Reputation: 940

You could use the die() function in PHP to do this like so.

mysqli_connect("localhost","root","","db_name")or die(require("404.php"));

That will attempt to connect to your database and if it fails will require another file, you could also create a function that redirects users and stick that inside the die() function and simply redirect them to another page, either way that's how you would send users away upon an error with the connection.

Upvotes: 0

Related Questions