Friday, 17 August 2007

Using Queries in PHP


This section, we will discuss more detailed about using queries in PHP for retrieving data from Mysql. As we know that for queri-ing something from Mysql in PHP, we must use mysql_query.

Let us see the following example:



NameGenderJob
JaneFemaleStudent
DianaFemaleStudent
JohnMaleStudent


According to the above table, if we want to show all data of the table. So we can use the following syntax:

include"connection.inc.php";
$strsql=mysql_query("SELECT * FROm t_student"); //assume that the table's name is t_student
while($data=mysql_fetch_array($strsql))
{
echo $data[name];
echo $data[gender];
echo $data[job];
}
?>

Connect Mysql in PHP

Previous section, we have already known that Mysql is a database for website. Now this section, we will discuss more detail about how to make a connection in PHP to Mysql for accessing data there.

Syntax for opening a connection in PHP is very simple as we see below:
$hostname="localhost";
$username="root"; // use username in phpmyadmin
$password="12345";// use password in phpmyadmin
$database="dblearn";// name of the database that we want to connect to
$strconnect=mysql_connect($hostname,$username,$password);
if($strconnect)
{
// if connection is made so we will select database to connect
mysql_selectdb($database,$strconnect);
}
else
{
// if connection is failed so we will display the error message
echo mysql_error();
}
?>


The syntax is very simple, isnt it? Remember to start php code, we must begin with .

by Google