www.pickatutorial.com Computer Tutorials

PHP connecting to MySQL Databases. Free online PHP and MySQL Web Database Programming Tutorial...

Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script
Lessons PHP Connecting MySQL Bookmark and Share
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
The free and open-source MySQL database is very often used with PHP. Before we can store and / or access data in a database, we must create a connection to the database. PHP provides us a function mysql_connect() to do just that. Its syntax follows:

mysql_connect(servername, username, password);

Parameters:
Servername: Specifies the database server to connect to. This is optional. If we do not provide the servername, it defaults to "localhost:3306".
Username: Specifies the usernamme to use to log in to the database server. This one is also optional. If we do not provide a username it defaults to the name of the user that owns the server process.
Password: Specifies the password to log in with. This is also optional. If we do not provide a password, it defaults to "".

Example
Followig is a very simple example that shows us how to connect to a MySQL database in PHP:

<?php
$con = mysql_connect("localhost", "adam", "ada");
if (!$con)
{
die('Error connecting database!');
}
// some code
?>


In the above example the database connection handler, returned by the mysql_connect() function, is stored in a variable $con for later use in the script. Please note that the die() part is executed in case the connection to the database fails.

Closing MySQL Connection
The connection the database automatically closes as and when the script ends. If we need to close the connection before the script ends, we use the mysql_close() function as under:

<?php
$con = mysql_connect("localhost", "adam", "ada");
if (!$con)
{
die('Error connecting database!');
}
// some code
mysql_close($con); // close the database connection
?>



Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.