Tuesday, 15 January 2013

Database Connection in Php | PHP Toutorial For beginners


After knowing the basic structure of php, next step is how to connect to the mysql database. To perform basic queries from within MySQL is very easy.This tutorial of phpcodeforbeginners will show you mysql database connection in php.

The first thing to do is connect to the database. To connect to mysql databse we use function mysql_connect().
Syntax of mysql_connect():-
mysql_connect(hostname, username, password)

Here "hostname" is name of your host(like 'localhost'), "username" is username of your host(For localhost it is 'roo') and "password" is password of your host site(Default is '').
Example:-
<?php
$hostname = "localhost";
$username = "root";
$password = "";

$conn = mysql_connect($hostname, $username, $password) or die("Unable to connect");
echo "Connected to MySQL";
?>

After successfull connection you should see "Connected to MySQL" when you run this script. If you can't connect to the server, make sure your password, username and hostname are correct.

Now we have created connection object, next step is to select a database to work with. To select database we use function mysql_select_db() with connection object.

Example:-
<?php
//selecting a database with name phptutorials.
$database = mysql_select_db("phptutorials",$conn)
  or die("Could not select phptutorials");
?>

Now database is selected, let's try and run some queries. The function used to perform queries is named - mysql_query(). The function returns a resource that contains the results of the query, called the result set. To examine the result we're going to use the mysql_fetch_array function, which returns the results row by row.

Example:-
<?php
$result = mysql_query("SELECT id, name, address FROM students");
while ($row = mysql_fetch_array($result)) {
   echo "ID:".$row{'id'}." Name:".$row{'name'}." Address:".$row{'year'}."<br>";
}
?>

Finally, we close the connection.

<?php
mysql_close($conn);
?>

Here is the full code:

<?php
$hostname = "localhost";
$username = "root";
$password = "";

//connection to the database
$conn = mysql_connect($hostname, $username, $password) or die("Unable to connect");
echo "Connected to MySQL";

//select database phptutorials
$database = mysql_select_db("phptutorials",$conn) or die("Could not select phptutorials");

//execute the SQL query and return records
$result = mysql_query("SELECT id, name, address FROM students");

//fetch tha data from the database
while ($row = mysql_fetch_array($result)){
   echo "ID:".$row{'id'}." Name:".$row{'name'}." Address:".$row{'year'}."<br>";
}
//close the connection
mysql_close($conn);
?>

No comments:

Post a Comment