Wednesday, November 5, 2008

PHP - Mysql, database access

How to get data from mysql database using php?

student Table (consider this table already in database - school and having the following data)
---------------
s_no | name
---------------
1 | Regin
2 | Beschi
3 | Siva
4 | Karthik
----------------

then the code to display data:
$con = mysql_connect("localhost","root",""); //local
//for server - mysql_connect("hostname/ip","username","password")
if($con)
mysql_select_db("school",$con); //database name

$sql = "select * from student";
$rsd = mysql_query($sql);
$total_students = mysql_num_rows($rsd); //total number of records in student table
while($rs = mysql_fetch_array($rsd))
{
echo $rs['s_no']." - ".$rs['name'];
echo "
";
}

mysql_close();
?>

Output:
1 - Regin
2 - Beschi
3 - Siva
4 - Karthik

This is a simple way to connect with a database.

Cheers!

No comments: