简体   繁体   中英

Use switch case to call php function

I have an ajax call that passes variables into the GET, this works fine as the echoes in comments appear fine however the echoes in the addProduct function do not get echoed even though i've passed the variables as arguments.

 $func = $_GET ['func'];

    $name =  $_GET ['name'];
    $desc = $_GET ['desc'];
    $photo = $_GET ['photo'];
    $price = $_GET ['price'];
    $cat =  $_GET ['cat'];

//These work fine
    //echo "add";
    //echo $name;
    //echo $desc;
    //echo $photo;
    //echo $price;
    //echo $cat;

    switch ($func) {
        case "add"     :  addProduct($name, $desc, $photo, $price, $cat);
        break;
        case "edit"    :  editProduct();
        break;
        case "remove"  :  editProduct();
        break;
    };

    function addProduct($name, $desc, $photo, $price, $cat) {
        echo "add";
        echo $name;
        echo $desc;
        echo $photo;
        echo $price;
        echo $cat;

    }

From reading the comments, I think you forgot a & in your url.

Instead of what you probably have:

myurl.com?func=addname=name&desc=desc&photo=photo

You need to use:

myurl.com?func=add&name=name&desc=desc&photo=photo

It was a silly error in my AJAX call. I had written a variable twice. Using var_dump() helped! Thanks for the help.

Your switch statement is not correctly entering the right case , so therefore your addProduct method is never called.

You will need to ensure that $func == 'add' so it enters the add case and calls the method.

I have tested your code. It prints as expected if $func = 'add'. Check $_GET['func'].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM