How to connect to your MySQL database from a PHP document ?
How to connect to your MySQL database from a PHP document ?
You can open a connection to your MySQL database from PHP using the mysql_connect() function. Here is an example:
The first variable (shown as your.hostaddress.com) is the location of your database. Often this is "localhost". The next two variables are your username and password. This is the login you use for your MySQL database.Code:<?php mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()) ; mysql_select_db("Database_Name") or die(mysql_error()) ; ?>
In the second line, we choose which database you are connecting too. This is needed because the same MySQL username can be linked to several databases.
Once you have connected to the database, you can run any SQL code to access and interact with the information in the database.
Opening a connection to MySQL database from PHP is easy. Just use the mysql_connect() function like this
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'petstore';
mysql_select_db($dbname);
?>
$dbhost is the name of MySQL server. When your webserver is on the same machine with the MySQL server you can use localhost or 127.0.0.1 as the value of $dbhost. The $dbuser and $dbpass are valid MySQL user name and password.
Don't forget to select a database using mysql_select_db() after connecting to mysql. If no database selected your query to select or update a table will not work.
Closing the Connection
The connection opened in a script will be closed as soon as the execution of the script ends. But it's better if you close it explicitly by calling mysql_close() function. You could also put this function call in a file named closedb.php.
Source code : closedb.phps
<?php
// an example of closedb.php
// it does nothing but closing
// a mysql database connection
mysql_close($conn);
?>
Now that you have put the database configuration, opening and closing routines in separate files your PHP script that uses mysql would look something like this :
<?php
include 'config.php';
include 'opendb.php';
// ... do something like insert or select, etc
include 'closedb.php';
?>
Bookmarks