你会用事务处理这个案子吗?

jucafojl  于 2021-06-25  发布在  Mysql
关注(0)|答案(0)|浏览(205)

根据试验结果 SELECT COUNT 我分配 userRole ,其中1是 foreign key of admin ,2是 foreign key of useruserRoles table ,然后我 insert 用户表中的数据。这是一个很好的例子吗 transaction 自从我的 insert depends on the result of select ?

try {

        // connect to the database
        require_once 'connect.php';
        // create a query to check if there are any records in the users table
        $querySelect = $conn->prepare("SELECT COUNT(userId) FROM users");
        // run the query
        $querySelect->execute(); 
        // fetch the result as an array indexed by column number as returned in the result set and turn it into a string
        $sajResult = json_encode( $querySelect->fetch(PDO::FETCH_NUM) ); 
        $sajResult === '["0"]' ?  $sUserRole = 1 : $sUserRole = 2;
        // create another query to insert into users
        $queryInsert = $conn->prepare("INSERT INTO users ( userName, firstName, lastName, password, image, 
        userRoles_roleId  ) VALUES ( :userName, :firstName, :lastName, :password, :image, :userRole )");
        $queryInsert->bindParam( ':userName' , $sUserName );
        $queryInsert->bindParam( ':firstName' , $sFirstName );
        $queryInsert->bindParam( ':lastName' , $sLastName );
        $queryInsert->bindParam( ':password' , $sPassword );
        $queryInsert->bindParam( ':image' , $sImage );
        $queryInsert->bindParam( ':userRole' , $sUserRole );
        // run the query
        $bResult = $queryInsert->execute();
        // send response to the client if the query is true or false
        $sjResponse = $bResult ? '{"status":"ok"}' : '{"status":"error"}'; 
        echo $sjResponse; 

    } catch (Exception $e) {

        echo "ERROR";

    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题