简体   繁体   English

使用事务插入和更新同一表

[英]Insert and update same table with transactions

Since I can't/don't know how to auto_increment two columns in one table I trying to do this with transactions. 由于我无法/不知道如何在一个表中自动递增两列,因此尝试使用事务来做到这一点。 This is what I trying 这就是我的尝试

$pdo->beginTransaction();
try 
{
       $sql = "INSERT INTO users ( username, password, firstname, lastname, email, user_image, path)
                    VALUES (:username, :password, :firstname, :lastname, :email, :user_image, :path)";

       $q = $pdo->prepare($sql);
       $q->execute(array(
                    ':username' => $username,
                    ':password' => sha1($password),
                    ':firstname'    => $firstname,
                    ':lastname' => $lastname,
                    ':email'    => $email,
                    ':user_image'   => $forDB,
                    ':path'     => $path,
                    ));                     

       $lastInsertID = $pdo->lastInsertId();
       $sql = $pdo->prepare("INSERT INTO users (usertype) 
                            VALUE (:user_id)");
       $sql->execute(array(
                    ':user_id'      => $lastInsertID
                    ));
       $pdo->commit();      
            }               
                // any errors from the above database queries will be catched
            catch (PDOException $e)
            {
                    // roll back transaction
                    $pdo->rollback();
                    // log any errors to file
                    ExceptionErrorHandler($e);
                exit;
            }

So basically I want to insert in column usertype the ID of this record (user_id) both columns must be equal. 所以基本上我想在列中插入usertype此记录(USER_ID)的ID两列必须相等。 Now when I try with this .. it is save empty fields except for the usertype which is updated with lastInsertID 现在,当我尝试使用此..时,将保存空字段,但使用usertype更新的用户lastInsertID

Change 更改

$sql = $pdo->prepare("INSERT INTO users (usertype) 
                    VALUE (:user_id)");

to this 对此

$sql = $pdo->prepare("UPDATE users SET usertype=:user_id WHERE user_id=:user_id");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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