2015-01-13 61 views
0

因爲我不知道如何在一個表中自動增加兩列,所以我試圖用交易來做到這一點。這是我想使用交易插入和更新同一個表

$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; 
      } 

所以基本上我想在usertype列中插入該記錄(USER_ID)兩列必須相等的ID。 現在,當我嘗試用這個..它是保存除了usertype這與lastInsertID

+0

我沒有看到beginstransaction – Robert

+0

用完整的代碼更新 – Goro

回答

1

變化更新的空字段

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

這個

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

是的,這使得伎倆。謝謝! – Goro