Connect and Insert Record to MYSQL using PHP !!

Started by ram, Jul 27, 2008, 02:27 PM

Previous topic - Next topic

ram

Hi [you],

Connect and Insert Record to MYSQL using PHP

php and mysql database connectivity

Sample Code

  1.
       //Connect and Insert Record to MYSQL using PHP
   2.
      CREATE TABLE items (
   3.
      itemID int(11) NOT NULL auto_increment,
   4.
      itemName varchar(255) NOT NULL default '',
   5.
      itemPrice float NOT NULL default '0',
   6.
      PRIMARY KEY (itemID) ) TYPE=MyISAM;
   7.
      INSERT INTO items VALUES (1, 'Paperweight', '3.99');
   8.
      INSERT INTO items VALUES (2, 'Key ring', '2.99');
   9.
      INSERT INTO items VALUES (3, 'Commemorative plate', '14.99');
  10.
      INSERT INTO items VALUES (4, 'Pencils (set of 4)', '1.99');
  11.
      INSERT INTO items VALUES (5, 'Coasters (set of 3)', '4.99');
  12.
  13.// space     
  14.     
  15.
      <html>
  16.
      <head></head>
  17.
      <body>
  18.
      <?php
  19.
      // open connection to MySQL server
  20.
      $connection = mysql_connect('localhost', 'guest', 'pass') ?
  21.
      or die ('Unable to connect!');
  22.
      // select database for use
  23.
      mysql_select_db('db2') or die ('Unable to select database!');
  24.
      // create and execute query
  25.
      $query = 'SELECT * FROM items';
  26.
      $result = mysql_query($query) ?
  27.
      or die ('Error in query: $query. ' . mysql_error());
  28.
      // check if records were returned
  29.
      if (mysql_num_rows($result) > 0)
  30.
      {
  31.
      // print HTML table
  32.
      echo '<table width=100% cellpadding=10 cellspacing=0 border=1>';
  33.
      echo
  34.
      '<tr><td>ID</td><td>Name</td><td>Price</td></tr>';
  35.
      // iterate over record set
  36.
      // print each field
  37.
      while($row = mysql_fetch_row($result))
  38.
      {
  39.
      echo '<tr>';
  40.
      echo '<td>' . $row[0] . '</td>';
  41.
      echo '<td>' . $row[1] . '</td>';
  42.
      echo '<td>' . $row[2] . '</td>';
  43.
      echo '</tr>';
  44.
      }
  45.
      echo '</table>';
  46.
      }
  47.
      else
  48.
      {
  49.
      // print error message
  50.
      echo 'No rows found!';
  51.
      }
  52.
      // once processing is complete
  53.
      // free result set
  54.
      mysql_free_result($result);
  55.
      // close connection to MySQL server
  56.
      mysql_close($connection);
  57.
      ?>
  58.
      </body>
  59.
      </html>