我使用if else然后在语法中出错

时间:2015-11-24 16:21:42

标签: php mysql sql

我正在尝试更新,如果存在其他插入,但我收到错误这是我的查询:

            IF EXISTS
            (
                SELECT * FROM pages_staff 
                WHERE pages_admin_page = :page
                AND pages_admin_type = :type
                AND pages_admin_user = :user
            ) 
            THEN 
            BEGIN 
                UPDATE pages_staff
                SET pages_admin_page = :page,
                    pages_admin_type = :type,
                    pages_admin_user = :user,
                    pages_admin_permissions = :permission
                WHERE pages_admin_page = :page
                AND pages_admin_type = :type
                AND pages_admin_user = :user
            END
            ELSE 
            BEGIN
                INSERT INTO pages_staff
                (
                    pages_admin_page,
                    pages_admin_type,
                    pages_admin_user,
                    pages_admin_permissions
                )
                VALUES
                (
                    :page, 
                    :type, 
                    :user, 
                    :permission
                );
            END

这是我的PHP:

    //iniate sql
    $add_staff = $database->prepare($sql);  

    //bind params
    $user = Session::get('id');
    $add_staff->bindParam(":page", $page, PDO::PARAM_INT);
    $add_staff->bindParam(":type", $type, PDO::PARAM_STR);
    $add_staff->bindParam(":user", $user, PDO::PARAM_INT);

    //what permission are they being given
    switch($permission):
        case 'admin':
            $permission = 'admin';
        break;
        case 'editor':
            $permission = 'editor';
        break;
        case 'moderator':
            $permission = 'moderator';      
        break;
        case 'advertiser':
            $permission = 'advertiser';
        break;
        case 'analyst':
            $permission = 'analyst';
        break;
        default: exit;
    endswitch;

    //bind last param and execute
    $add_staff->bindParam(":permission", $permission, PDO::PARAM_STR);
    $add_staff->execute();

但我收到了错误

  


警告:PDOStatement :: execute():SQLSTATE [42000]:   语法错误或访问冲突:1064 SQL中有错误   句法;查看与MySQL服务器版本对应的手册   在'IF EXISTS附近使用正确的语法                 (                     SELECT * FROM pages_staff                     在 C:\ xampp \ htdocs \ application \ model \ EmployeesModel.php 上的第1行的pages_admin_page ='    468
{{“成功”:false,“错误”:“添加时出错   对此用户的权限“}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

使用out32dll

insert on duplicate key update

然后使用唯一索引/约束来防止重复:

INSERT INTO pages_staff(pages_admin_page, pages_admin_type, pages_admin_user, pages_admin_permissions)
    VALUES (:page, :type, :user, :permission)
ON DUPLICATE KEY UPDATE pages_admin_permissions = :permission;