How to create a MySQL connection

Connecting to MySQL is an important first step for dynamic web applications. If the MySQL connection fails, then you cannot run database queries.

A good exercise when using databases is to set the server host, username, password and database name at the beginning of the code (script). To make it easier and avoid looping when connecting, it's better if the code is stored in one file only. If there is a change, then you only need to change the code in one file only.

$localhost = "your_host";
$username="your_username";
$password="your_password";
$database="database_name";

You must replace “your_host”, “your_username”, “your_password”, “database_name” with , MySQL host, MySQL username & password and the database that will be used for your script.

You may be wondering if there is a security risk to keeping your passwords on file. You don't have to worry because the PHP source code is processed by the server before being sent to the browser. So visitors will not see your application code (script).

Next you need to connect to the database with a PHP script. This can be done with the mysql_connect function:

mysql_connect($localhost,$username,$password);

This line tells PHP to connect to the MySQL database server that you set at the beginning of the code.

After the connection is established, you need to select the database that you will use. The database you use must match the username that has access rights to the database. This can be done via the following command:

@mysql_select_db($database) or die("unable to connect database");

This command tells PHP to select the database you have set with the $database variable at the start of the code. If the script fails to connect, it will display an error message:

Can't connect database

function or die(); function returns the debug result of the executed function.

Other important PHP functions:

mysql_close();

This function is very important to stop the connection to the database server. Your script will still run if you don't include this function. And if you don't stop the connection (many connections connected) it will create problems on your website. a good practice is to stop all MySQL connections after executing a query.

Through the above command, you have successfully connected to the MySQL server and are ready to query other databases.

Was this answer helpful?

Related Articles

How to build a website using Sitepad Website Builder

Sitepad website builder is a professional website builder feature that is very easy to use. This...

How to transfer Files via Filezilla

FileZilla or also known as FileZilla Client, is a free, open source, cross-platform FTP software....

Reinstall Wordpress without losing data

Is it possible to re-install wordpress on hosting without losing any data at all?. Yes, you do...