Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if PHP is connected to a database already?

Tags:

php

mysql

Basically in pseudo code I'm looking for something like

if (connected_to_any_database()) {     // do nothing } else {     mysql_connect(...) } 

How do I implement

connected_to_any_database() 
like image 701
deltanovember Avatar asked Feb 28 '11 21:02

deltanovember


People also ask

How can I tell if my database is connected in PHP?

Firstly, use the mysqli_xxx() functions instead of the old obsolete mysql_xx() functions. With the mysqli library, you get a variable that contains your DB connection, which you can examine at any point. $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

How can I check my database connection?

To test the connection to your database, run the telnet hostname port on your Looker server. For example, if you are running MySQL on the default port and your database name is mydb, the command would be telnet mydb 3306 .

How do I know if MySQL connection is working?

We check the status with the systemctl status mysql command. We use the mysqladmin tool to check if MySQL server is running. The -u option specifies the user which pings the server. The -p option is a password for the user.

How can I find database in PHP?

Open phpMyAdmin and Click on database which you want to you want to upload to the server. then click on Export option and then choose SQL and press go. It will create the . sql file which contains all the queries which will create exact copy of your database on server.


2 Answers

Have you tried mysql_ping()?

Update: From PHP 5.5 onwards, use mysqli_ping() instead.

Pings a server connection, or tries to reconnect if the connection has gone down.

if ($mysqli->ping()) {   printf ("Our connection is ok!\n");  } else {   printf ("Error: %s\n", $mysqli->error);  } 

Alternatively, a second (less reliable) approach would be:

$link = mysql_connect('localhost','username','password'); //(...) if($link == false){     //try to reconnect } 
like image 89
mailo Avatar answered Sep 27 '22 20:09

mailo


Try using PHP's mysql_ping function:

echo @mysql_ping() ? 'true' : 'false'; 

You will need to prepend the "@" to suppose the MySQL Warnings you'll get for running this function without being connected to a database.

There are other ways as well, but it depends on the code that you're using.

like image 41
McHerbie Avatar answered Sep 27 '22 22:09

McHerbie