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.
$localhost = "host_anda"; $username="username_anda"; $password="password_anda"; $database="nama_database";
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("tidak bisa konek 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.