如何在彼此之后执行多个查询?

时间:2017-12-01 14:06:03

标签: php mysql

当用户填写注册表单并点击前端的注册按钮时,应该会发生以下情况。它应该将所有用户信息从输入字段保存到users表,然后检查userRole表中是否存在任何记录,如果没有插入admin,如果是,则插入user在userRole列中。

基本上是一次插入,一次选择和一次插入。 我不知道如何设置这个,所以这是有效的。现在只在userRole表中插入值用户。

 <?php

    // Get the userimage and save it with a unique id
    $sFileExtension = pathinfo($_FILES['fileUserImage']['name'], PATHINFO_EXTENSION);
    $sFolder = 'img_webshop/';
    $sFileName = 'userimage-'.uniqid().'.'.$sFileExtension;
    $sSaveFileTo = $sFolder.$sFileName;
    move_uploaded_file( $_FILES['fileUserImage']['tmp_name'], $sSaveFileTo);

    try {

                // connect to the database
                require 'connect.php';
                // create a query
                $sUserName = $_POST['txtEmailorPhoneNumber'];
                $sFirstName = $_POST['txtFirstName'];
                $sLastName = $_POST['txtLastName'];
                $sPassword = $_POST['txtPassword'];
                $sImage = $sFolder.$sFileName;
                $query1 = $conn->prepare("INSERT INTO users ( userName, firstName, lastName, password, image ) VALUES ( :userName, :firstName, :lastName, :password, :image )");
                $query1->bindParam( ':userName' , $sUserName );
                $query1->bindParam( ':firstName' , $sFirstName );
                $query1->bindParam( ':lastName' , $sLastName );
                $query1->bindParam( ':password' , $sPassword );
                $query1->bindParam( ':image' , $sImage );
                // run the query
                $aResult = $query1->execute();
                $query2 = $conn->prepare("SELECT COUNT ( userRole ) as total FROM userRoles");
                $bResult = $query2->execute();
                if ($bResult === 0 ) {
                    $sUserRole = 'admin';
                }
                else {
                    $sUserRole = 'user';
                }
                $query3 = $conn->prepare("INSERT INTO userRoles ( userRole ) VALUES ( :userRole )");
                $query3->bindParam( ':userRole' , $sUserRole );
                $cResult = $query3->execute();
                $sjResponse = $cResult ? '{"status":"ok"}' : '{"status":"error"}';
                // $lastId = $query->lastInsertId();
                // $result = json_encode( $query->fetch(PDO::FETCH_ASSOC) );

                echo $sjResponse; 


            } catch (Exception $e) {

                echo "ERROR";

            }

    ?>

1 个答案:

答案 0 :(得分:0)

改变这个:

&#13;
&#13;
if ($bResult === 0 ) {
$sUserRole = 'admin';
}
else {
 $sUserRole = 'user';
}
&#13;
&#13;
&#13;

对此:

&#13;
&#13;
if ($bResult > 0 ) {
$sUserRole = 'user';
}
else {
 $sUserRole = 'admin'; 
}
&#13;
&#13;
&#13;

这应该解决它!