Friday, September 25, 2009
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.
$host = "localhost";//127.0.0.1
$user_name = "root";
$password = "1234";
$database = "test_db";
$con = mysql_pconnect($host,$user_name,$password);
$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>");
print("Database does not exists");
print("Error: unable to connect");
Posted by Duminda Chamara at 3:15 AM