Duminda Chamara

Friday, September 25, 2009

My SQL Database Connecting using PHP

How Connect to a mysql database and read table data in PHP?


Use the following code to connect to a mysql database and retrieve retrieve data and print as a table.


First you have to create a connection to the mysql databse. use mysql_pconnect function to connect to the mysql databse. You have to specify host name (the server which is the database hosted) user name (dabase user name) and the password .


mysql_select_db function is use to select the mysql database that you want to connect. Here you have to specify valid mysql database name and the connection that mentioned above.


mysql_query function is use to execute a sql statement against the mysql databse.


mysql_fetch_array function is use to retrieve data from the executed sql query. It returns row by row during the execution in the while loop. 


mysql_close function is used to close the connection that have already open to the mysql database server.


<?php


$host = "localhost";//127.0.0.1
$user_name = "root";
$password = "1234";
$database = "test_db";


$con = mysql_pconnect($host,$user_name,$password);


if($con!=NULL){
$db=mysql_select_db($database,$con);

if($db!=NULL){
$sql  = "SELECT user_id,first_name,last_name FROM test_table";
$result = mysql_query($sql,$con);
print("<table border='1'> <th>User ID</th> <th>First Name</th> <th>Last Name</th>");
while($row=mysql_fetch_array($result)){
print("<tr>");
print("<td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</tr>");
}
print("</table>");
mysql_close($con);
}else{
print("Database does not exists");
mysql_close($con);
}
}else{
print("Error: unable to connect");
}
?>

0 comments: