Basics of using Case's in PHP


Hello all,
Do you use PHP? Perhaps a beginner yes? I know from exprience for one PHP function i would have about 2/3 or more files, then i discovered Cases's.

Your probly looking at this like what the ....? Here i will break it down for you.

PHP Code:
PHP Code
  1. <?
  2. include("config.php");
  3.  
  4. switch($_GET['view']) {
  5. case "delete" :
  6. include("sql.php");
  7.  
  8. $id = $_GET['id'];
  9. if(!$_GET['id'])
  10. {
  11. header("Location:bugs.php");
  12. }
  13. $select = mysql_query("select * from `form` where id=$id");
  14. if (mysql_num_rows($select) == "0") {
  15. echo 'Unable to find the message info in the database!';
  16. exit();
  17. }
  18. $delete = mysql_query("DELETE FROM `form` WHERE id = '$id'") or die(mysql_error());
  19. echo("<meta http-equiv=\"Refresh\" content=\"1; URL=bugs.php\"/>The Bug report has been deleted! You will now be redirected");
  20. break;
  21. default:
  22. include("sql.php");
  23. $sql = mysql_query("SELECT * FROM `form` WHERE type='5'");
  24. while($r = mysql_fetch_array($sql))
  25. {
  26. $id = $r[id];
  27. $name = $r[user];
  28. $email = $r[email];
  29. $message = $r[msg];
  30. $ip = $r[ip];
  31. echo("
  32. $id. $name
  33.  
  34. $email
  35.  
  36. $message
  37.  
  38. $ip
  39.  
  40. <a href=\"bugs.php?view=delete&id=$id\">Delete</a><hr>");
  41. }
  42. break;
  43. ?>

Ok so in this instance the file is bugs.php, Once the delete it would send the url "bugs.php?view=delete&id=$id".

the ?view=delete will run this function. Deleteing the form in that database that is equal to the ID!

PHP Code:
PHP Code
  1. include("sql.php");
  2.  
  3. $id = $_GET['id'];
  4. if(!$_GET['id'])
  5. {
  6. header("Location:bugs.php");
  7. }
  8. $select = mysql_query("select * from `form` where id=$id");
  9. if (mysql_num_rows($select) == "0") {
  10. echo 'Unable to find the message info in the database!';
  11. exit();
  12. }
  13. $delete = mysql_query("DELETE FROM `form` WHERE id = '$id'") or die(mysql_error());
  14. echo("<meta http-equiv=\"Refresh\" content=\"1; URL=bugs.php\"/>The Bug report has been deleted! You will now be redirected");

Now if we did not stop this it would completely mess up, be bad coding .. and personally i hate dodgey code.

PHP Code:
PHP Code
  1. break;


This will end the case function once it has done what it is suppose to do ...

Ok well that about sums up my tutorial on Case's in PHP. Ill be happy to answer any questions.

Yours, Adam
Overload's Avatar
Author:
Views:
2,006
Rating:
Posted on Tuesday 13th March 2007 at 04:15 PM
MOD-Dan
MOD-Dan's Avatar
cool looks good!