PHP MySQL tutorial - PHP MySQL database example


Home - Tutorials - Databases

In this PHP MySQL tutorial I will show you how to use basic database manipulation features in PHP.

Tutorial info:


Name:PHP MySQL tutorial
Total steps:5
Category:Databases
Level:Beginner

Bookmark PHP MySQL tutorial



Bookmark and Share

Step 5 - PHP MySQL database example


PHP MySQL tutorial

Here you can find a complete code which demonstrates all the 4 basic SQL statements and how to use PHP to modify data in a MySQL database.
 

Code:
  1. <?php
  2. mysql_connect("localhost", "username", "password") or die(mysql_error());
  3.  
  4. echo "<br/>Step 1. Insert data<hr/>";
  5. $sql = "INSERT INTO users (name,city,web,age) VALUES ('Tom','Vegas','www.tom.com',5)";
  6. $result = mysql_query($sql);
  7.  
  8. if ($result){
  9. echo "Data was inserted!<br/>";
  10. } else {
  11. echo "An error occured during insert!<br/>";
  12. }
  13.  
  14. $result = mysql_query("SELECT * FROM users");
  15.  
  16. while($row = mysql_fetch_assoc($result)){
  17. echo "ID: ".$row['id'].", Name:".$row['name']
  18. .", City:".$row['city'].", Age:".$row['age']."<br/>";
  19. }
  20.  
  21. echo "<br/>Step 2. Update data<hr/>";
  22. $sql = "UPDATE users SET age=45 WHERE name='Tom'";
  23. $result = mysql_query($sql);
  24.  
  25. if ($result){
  26. echo "Data was updated!<br/>";
  27. } else {
  28. echo "An error occured during update!<br/>";
  29. }
  30.  
  31. $result = mysql_query("SELECT * FROM users");
  32.  
  33. while($row = mysql_fetch_assoc($result)){
  34. echo "ID: ".$row['id'].", Name:".$row['name']
  35. .", City:".$row['city'].", Age:".$row['age']."<br/>";
  36. }
  37.  
  38. echo "<br/>Step 3. Remove data<hr/>";
  39. $sql = "DELETE FROM users WHERE name='Tom'";
  40. $result = mysql_query($sql);
  41.  
  42. if ($result){
  43. echo "Data was removed!<br/>";
  44. } else {
  45. echo "An error occured during remove!<br/>";
  46. }
  47.  
  48. $result = mysql_query("SELECT * FROM users");
  49.  
  50. while($row = mysql_fetch_assoc($result)){
  51. echo "ID: ".$row['id'].", Name:".$row['name']
  52. .", City:".$row['city'].", Age:".$row['age']."<br/>";
  53. }
  54.  
  55. ?>





Previous Step of PHP MySQL tutorial


Tags: php mysql tutorial, php mysql, php database, php, mysql, tutorial



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0312