Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, February 16, 2011

Retrieving Data from MySQL DataBase with PHP

A ton of websites use PHP and MySQL for web development and most of the time they are built around some Content Management System that handles database interaction. However, if you are interested in learning how to simply interact with the database using php, then I will provide a nice example. The PHP mysql_fetch_array() function returns an array of the requested data from the table. Then, a while loop assigns a row’s data to an array called $row and the value associated with the column name on each row is written out. The following php code is modified from a Mike McGrath’s PHP for WINDOWS and LINUX book:

[sourcecode language="php"]
<html><head><title>Get Data</title></head>
<body>

<?php
#connect to MySQL
$conn=@mysql_connect("localhost","user","password") or die("Err:conn");

#select the specified database
$rs=@mysql_select_db("database_name", $conn) or die("Err:Db");

#create the query
$sql="select id,cat_name from table";

#execute the query
$rs=mysql_query($sql,$conn);

#write the data
while( $row = mysql_fetch_array($rs) )
{
echo("ID: ".$row["id"]);
echo(" Print Data: ".$row["cat_name"]."<br>");
}
?>
</body>
</html>
[/sourcecode]

I tested the script and it works great. Make sure that the table exists in your database and it has what you are trying to pull. I had something under id and something under cat_name in my table so it showed me the appropriate values. If you have questions, send me an email or comment.