Connecting to a MySQL Database

Dismounted

59.***.***.***
1,440 days ago

Connecting to a MySQL Database

Connecting to a MySQL Database Connecting to a MySQL database through PHP is very easy and also very important for all scripts that require MySQL. If you need your script to connect to a database, then you're going to need to combine variables and a simple code into your script. So lets get started, this is very easy and only requires you to add this code at the top of your script.

PHP code:

<?php // Begin Variables $db_user = "USERNAME"; // Replace "username" with your username $db_pass = "PASSWORD"; // Replace "password" with your password $db_host = "HOSTNAME"; // Replace "hostname" with your hostname (usually localhost) $db_name = "DATABASE"; // Replace "database" with your database name $db_table = "TABLE"; // Replace "table" with the table you want to use // End Variables // Begin MySQL Connection mysql_connect($db_host, $db_user, $db_pass); @mysql_select_db($db_name) or die ("Unable to select database!"); // End MySQL Connection ?>

After you replace all of that, add it you your script. Make sure at the end of your script add this code to close the connection.

PHP code:

<?php mysql_close(); ?>

penguinmama

75.***.***.***
1,358 days ago
What happens if one doesn't use mysql_close()? I haven't been using it in my scripts because I didn't realize it was necessary. Do I need to go back and add it into all my scripts?

bdm

213.***.***.***
1,306 days ago
it's better to add it on the end, it dealloc the resource. It's not too important to add it on simple connections , but for example if you use a locked table, till you don't disconnect ( close ) the lock still active.

Put it everytime it's a good beaviour :)