PHP Tutorials

MySQL Database Connection

Connecting to MySQL database

Connecting to MySQL database:

It is always a good practice to write the connection string for the database in a separate file and call it on each page where the the database is required. To know how to call the file see PHP Tips (Server Side Includes).

So we first create a file where we assign the values for your server, the database you want to connect,the user name and the password to variables. Let us save this file as conn.php

<?php
$strServer="66.9.65.200"; // Server IP Address Or Name
$strDatabase="database name"; // Database Name
$strUser="root"; // User ID
$strPwd="pwd";// Password
?>

Now we can call

The syntax to connect to the server or Opening a database connectivity is

$strDB=mysql_connect("ServerIP Address","Username","Password")

For the above example we would write

$strDB=mysql_connect($strServer,$struser,$strPwd);

To connect to the database the syntax is

mysql_select_db("Database Name",$strDB)

For the above example we would write

$database=mysql_select_db("strDatabase",$strDB)

The syntax for closing the Database connection is

mysql_close(Result Connection ID)

For the above example we would write

mysql_close($strDB)

On a whole the code would look like this

<?php
include("conn.php")
$strDB=mysql_connect($strServer,$struser,$strPwd);
$database=mysql_select_db("$strDatabase",$strDB);

mysql_close($strDB)
?>

conn.php

<?php
$strServer="66.9.65.200"; // Server IP Address Or Name
$strDatabase="databasename"; // Database Name
$strUser="root"; // User ID
$strPwd="pwd";// Password
?>

 

Please like, +1, link to and share this SmartWebby resource if you found it helpful. Thanks!