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.

2 comments:

  1. I am totally new to php.Actually, I have to reteriv data which is related to the keyword provide in search box. for this I have create a form in html in which a keyword is searched, and a php file containing codes for database connection,query construcion, excution of query and display of data.
    I would be thankful to you if u provide me with the solution.Thank you for help in advance!

    ReplyDelete
  2. i want to create form like product information & product id will be auto genrates & again i want to create small form like search product info based on product id when entered product id it shows all information related to that product in new form in php plz send me a php script with database.as soon as possible.

    ReplyDelete