Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing php / mysqli connection

Tags:

php

ubuntu

mysqli

I am looking for a way to test just the connection portion of a php / mysqli connection. I am migrating from a LAMP server build on Vista to the same on Ubuntu and am having fits getting mysqli to work. I know that all of the proper modules are installed, and PhpMyAdmin works flawlessly. I have migrated a site over and none of the mysqli connections are working. The error that I am getting is the "call to member function xxx() on non-object" that usually pops up when either the query itself is bad or the query is prepared from a bad connection. I know that the query itself is good because it works fine on the other server with the exact same database structure and data. That leaves me with the connection. I tried to write a very simple test connection and put it in a loop such as ..

if(***connection here ***) {
    echo "connected";
}
else { 
    echo "not connected"; 
}

It echoes "connected", which is great. But just to check I changed the password in the connection so that I knew it would not be able to connect and it still echoed "connected". So, the if / else test is clearly not the way to go....

like image 500
Blind Fish Avatar asked Sep 09 '10 16:09

Blind Fish


People also ask

How do I know if MySQLi is working?

Check if MySQLi is Installed The first step is to check if MySQLi extension is installed. You can do that by visiting a phpinfo() page that you made, or by running this command: php -m | grep mysqli.

How check connection is open in PHP?

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.

Why is MySQLi connect () used?

The mysqli_connect() function establishes a connection with MySQL server and returns the connection as an object.


2 Answers

For test php connection in you terminal execute:

$ php -r 'var_dump(mysqli_connect("localhost:/tmp/mysql.sock", "MYSQL_USER", "MYSQL_PASS",
     "DBNAME));'
like image 54
Cubiczx Avatar answered Nov 14 '22 04:11

Cubiczx


mysqli_connect() always returns a MySQLi object. To check for connection errors, use:

$mysqli_connection = new MySQLi('localhost', 'user', 'pass', 'db');
if ($mysqli_connection->connect_error) {
   echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else {
   echo "Connected.";
}
like image 24
Lekensteyn Avatar answered Nov 14 '22 04:11

Lekensteyn