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
config.inc.php
<?php
 //Example of using MySQL in PHP 
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "test";
$con=mysql_connect("$db_host","$db_username","$db_pass");
if($con)
{echo "connect to MySQL server ".$db_host."<br />";}
else die ("could not connect to mysql");
if(mysql_select_db("$db_name"))
{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
 <?php
 include('config.inc.php');
 $query = "SELECT * from guestbook";
 $result = mysql_query($query);
   //Fetch  each row
 while($thisrow=mysql_fetch_row($result))
  {
      $i=0;
      //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] . " "; 
       $i++;
      }
   echo "<br>";
  }
  mysql_close($con);
 
  ?>


4) Example of  mysql_fetch_array.
<?php
 include('config.inc.php');
 $query = "SELECT * from guestbook";
 $result = mysql_query($query);
  echo "<table border='1'>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    </tr>";

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

  mysql_close($con);
 ?>


Video of this tutorial

No comments:

Post a Comment