Code.GeekInterview.com
 
Code Samples PHP
 

Connect and Insert Record to MYSQL using PHP


Code ResourceAuthor: jijo chacko  

Difficulty Level:

Published: 6th Nov 2006   Read: 9595 times  

Filed in: PHP
Add Comment


 

 

Sponsored Links


 

 

php and mysql database connectivity

 


Sample Code
  1.  
  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.  
  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><b>ID</b></td><td><b>Name</b></td><td><b>Price</b></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>
  60.  
Copyright GeekInterview.com


Next Article: Get an email when google visits your Blog


 

Latest Code Samples

 

Popular Code Samples

 

Related Code Samples

 

Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    



Comments

nice script
Comment posted by: dhanush on 2006-11-06T09:03:00
welldone jijo you did a good work keep it up
Comment posted by: vinod on 2006-11-14T06:00:44
thanx for your work
thanx a lot.
Comment posted by: Mohammad Naseem on 2011-02-14T06:50:26

Popular Coders

# Coder NameHits
1. chowsys21573
2. jijo chacko9596
3. Lokesh M8332
4. jayantg3230

Active Coders

# Coder NameCodes
1. chowsys6
2. Lokesh M2
3. jayantg1
4. jijo chacko1

Refined Tags