Connect to any MySQL database using a HTML form

Nov 15, 2007 17:39 GMT  ·  By

There are many situations when you need to connect to various MySQL databases, but at the same time you have to change the variables needed for the connection script. You can solve this situation by using connection variables that can be modified with the help of a HTML form. This form will allow you to send the new values of the variables to the connection script.

Practically, you can connect to a MySQL database in various ways from PHP. In this article I propose a universal connection method that could be used in PHP/MySQL applications installation or could be integrated in any other PHP program that requires connections to different MySQL databases or servers.

The next listing (dbconnect.html) represents the HTML code of the form:

code
Database Host:

User Name:

Password:

Database Name:
For the default privileges values of any MySQL installation, the form fields corresponding to Database Host and respectively User Name must be filled in with localhost (127.0.0.1) and root. The Password field will stay empty, because the MySQL root account by default has no password assigned. In other situation, a connection with a remote MySQL server could be also established by specifying the server address and port in Database Host field.

In the Database Name field, you must insert the name of the database. In the next code listing (dbconnect.php), there are the PHP statements that form the connection to MySQL database script and a test query demonstrating the connection validity:

[CODE=0][CODE=1]

The function mysql_connect will establish the connection with the MySQL server by using the values of the connection variables ($dbhost,$user,$password)received from the HTML form. If the connection with the server is not established, then the error message "Connection refused by server" will be displayed. Finally, a database will be selected in order to perform queries on it (from variable value $dbname).

The sample query listed in the PHP script will output the names of all tables existing in the database. You can easily adapt this script to suit your own needs, as well as the HTML form. You can try to extend the script functionality by testing another type of queries for a certain MySQL database, such as view, add, edit, delete or search records. The script also represents a good start for a universal MySQL database interface. You should test the script by calling the HTML document, where you must fill in the form with your MySQL server and database connection variables values.