oceanier oceanier - 4 months ago 10
PHP Question

converting if else structure into switch case structure

I wanted to change my if else structure into switch case how shoul i change it into switch case.

<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","");
mysql_select_db("ocean");
if(isset($_GET['type']))
{
$res = [];


if($_GET['type'] =="add"){
$name = $_GET ['Name'];
$lname = $_GET['Lname'];
$userN = $_GET['User'];
$passW = $_GET['Pass'];
$gen = $_GET['Gender'];
$mail = $_GET ['Email'];
$mobile = $_GET ['Mobile'];
$address= $_GET['Address'];

$query1="select uid from oops where email='$mail'";
$result1= mysql_query($query1);
if( mysql_num_rows($result1)>0){
$res["flag"]= TRUE;
$rest["message"] = "There is already a user with that email!";
}else{
$query1 = "insert into oops(username, password, firstname, lastname, gender, email, mobile, address) values('$userN','$passW','$name','$lname','$gen','$mail','$mobile','$address')";
$result1 = mysql_query($query1);

if($result1)
{
$res["flag"] = true;
$rest["message"] = "Data Inserted Successfully";
}
else
{
$res["flag"] = false;
$rest["message"] = "Oppes Errors";
}
}

}
if($_GET['type'] =="edit") {
$id=$_GET['id'];
$name = $_GET ['Name'];
$lname = $_GET['Lname'];
$userN = $_GET['User'];
$passW = $_GET['Pass'];
$gen = $_GET['Gender'];
$mail = $_GET ['Email'];
$mobile = $_GET ['Mob'];
$address= $_GET['Address'];
//$id = $_GET['id'];
// echo var_dump($_GET);
$query1 =("UPDATE oops SET username = '$userN',password = '$passW', firstname= '$name',lastname='$lname',gender = '$gen', email = '$mail', mobile = '$mobile' , address = '$address' WHERE uid = '$id'")or die('fail to update');
$result1 = mysql_query($query1);
if($result1)
{
$res["flag"] = true;
$rest["message"] = "Data Updated Successfully";
}
else
{
$res["flag"] = false;
$rest["message"] = "Oppes Errors";
}
}
if($_GET['type'] == "delete"){
$id=$_GET['id'];

$query1=("DELETE FROM oops WHERE uid='$id'");
$result1= mysql_query($query1);
if($result1){
$res["flag"] = true;
$rest["message"] = "User deleted Successfully";
// header("location:client.php");
}
else{
$res["flag"] = false;
$rest["message"] = "Oppes Errors";
}
}

}

else{
$res["flag"] = false;
$rest["message"] = "Invalid format";
}

echo json_encode($rest);

?>


I don't know how do that and how do I store the value of
isset($_GET['type'])
value into variable on same page

Answer
switch($_GET['type']) {
    case "add":
        //do something
        break;
    case "delete": 
        // do something else etc

    default:
       //if none of the cases apply, do something here (same as else in if-elseif-else)
}