PHP - 如何在函数中使用 SWITCH

And*_*rew 2 php function switch-statement

我试图减少代码中选择语句、更新等的数量,所以我想我会尝试为此创建一个函数,但是我很困惑我的努力在第一个障碍中失败了。

我已经相当全面地搜索了这个问题(我觉得),我在我发现的例子中找不到任何差异。

这是我的功能,带有打印语句以帮助我诊断问题。

function select_statement($action, $table, $where){
print $action.' - ';

switch ($action){
    case 'select':
        print 'select used - ';
        $thequery = 'SELECT * FROM '. $table . ' WHERE '. $where;
    case 'insert':
        print 'insert used - ';
        $thequery = 'INSERT INTO '. $table;
    case 'update':
        print 'update used - ';
        $thequery = 'UPDATE ' . $table . ' SET ';
    }
print $thequery;
mysql_query($thequery);

}
Run Code Online (Sandbox Code Playgroud)

这是调用函数的行:-

$logins = select_statement('select', 'users', 'user_id=1');//calls function
Run Code Online (Sandbox Code Playgroud)

这是结果:-

select - select used - insert used - update used - UPDATE users SET 
Run Code Online (Sandbox Code Playgroud)

如您所见,代码正在触发每个打印语句,并且似乎忽略了“case”语句。

我真的不确定我在这里做错了什么?

Joh*_*nde 5

你忘了使用break. 没有它,每个 case 语句都将“落入”下一个语句并继续运行。break在每条case语句结束时停止执行`;

switch ($action){
    case 'select':
        print 'select used - ';
        $thequery = 'SELECT * FROM '. $table . ' WHERE '. $where;
        break;
    case 'insert':
        print 'insert used - ';
        $thequery = 'INSERT INTO '. $table;
        break;
    case 'update':
        print 'update used - ';
        $thequery = 'UPDATE ' . $table . ' SET ';
        break;
    }
Run Code Online (Sandbox Code Playgroud)