Sunday, January 30, 2011

MySQL PHP Exampler

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

No comments:

Post a Comment