Tuesday, December 18, 2012

Using MySQL In PHP Demo

Give a brief introduction how to connect to MySQL in PHP (mysql_connect), how to use mysql_fetch_row and mysql_fetch_array.
1) Connect to MySQL dataase
 //Example of using MySQL in PHP 
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "test";
{echo "connect to MySQL server ".$db_host."<br />";}
else die ("could not connect to mysql");
{echo "connect to dtabase ".$db_name."<br />";}
else die("no database");            

2) Create guestbook table and insert three rows
CREATE TABLE `guestbook` (
  `id` int(11) NOT NULL auto_increment,
  `FirstName` varchar(100) NOT NULL default '',
  `LastName` varchar(100) NOT NULL default '',
  UNIQUE KEY `id` (`id`)

INSERT INTO `guestbook` (`FirstName`,`LastName`)
VALUES ('John', 'Smith'), ('Tom', 'Lu'), ('Mike','Xu');

3) Example of  mysql_fetch_row
 $query = "SELECT * from guestbook";
 $result = mysql_query($query);
   //Fetch  each row
      //Fetch each column
      while ($i < mysql_num_fields($result))
       $field_name=mysql_fetch_field($result, $i);
       //Display all the fields on one line
       echo $thisrow[$i] . " "; 
   echo "<br>";

4) Example of  mysql_fetch_array.
 $query = "SELECT * from guestbook";
 $result = mysql_query($query);
  echo "<table border='1'>

  while($row = mysql_fetch_array($result))
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "</tr>";
  echo "</table>";


Video of this tutorial

No comments:

Post a Comment