Connecting to MYSQL DataBase

|

In order to pull information from a MySQL database to your php pages, you need to connect to the database first.

Syntax:

mysql_connect(servername,username,password);
servername: It specifies the server to connect to. Default value is "localhost:3306"
username: It specifies the username to log in with. Default value is the name of the user that owns the server process
password: It specifies the password to login. Default is ""
Note:
To execute the SQL statements we must use the mysql_query() function. This function is used to send a query or command to a MySQL connection.

Example:

$server = "localhost";
$user = "";
$pass = "";
$db = "mydb";

$conn = mysql_connect("$host", "$user", "$pass") or die ("Unable to connect.");
mysql_select_db("$db", $conn);
?>

Create a Database


PHP also provide a function to create MySQL database, mysql_create_db().
$con = mysql_connect("localhost:3306","adam","123456");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$query = "CREATE DATABASE mydb";
$result = mysql_query($query,$con);
?>