在PDO事务中创建表

时间:2017-07-13 21:42:02

标签: php mysql pdo

如何修复此事务以便pdo查询在步骤#4中创建新表?

前三个步骤有效,但我似乎无法让#4工作。

STEPS

  1. 在数据库中找到chatstatus为0的用户
  2. 将用户添加到数据库中(包含预定变量)
  3. 对于状态为0的用户和插入的用户
  4. ,将chatstatus从0更改为1

    4。创建一个表格,其中包含两个用户的ID作为标题,如2 + 13(2为id,13为id)

    $userid = "123456";
    $firstname = "Dae";
    $oglang = "engs";
    $status = 0; 
    
    $pdo->beginTransaction();
    
    try{
    
    
    
    
    
    // Find a user with a status of 0 
        $sql = "SELECT id FROM users WHERE chattingstatus = :status";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(':status' => $status)
        );
        $freeuser = $stmt->fetchColumn();
    
    
    //put the original user into the database with userid firstname and language
     $sql = "INSERT INTO users (userid, firstname, oglang, chattingstatus) VALUES (:userid, :firstname, :oglang, :chattingstatus)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(':userid' => $userid, ':firstname' => $firstname, ':oglang' => $oglang, ':chattingstatus' => 0)
        );
       $ogID = $pdo->lastInsertId();
    
    
    
    
    // change the chattingstatus of 0 of the free user to 1
        $sql = "UPDATE users SET chattingstatus = 1 WHERE id = :freeuser";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(':freeuser' => $freeuser)
        );
    
    //query 3  CHANGE STATUS OF ORIGINAL USER from 0 to 1 
        $sql = "UPDATE users SET chattingstatus = 1 WHERE userid = :oguser";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(':oguser' => $userid)
        );
    
    //query 4: Make a table between the 2 users with their IDs
    
    
        $table = $freeuser."+".$ogID; 
    
       $sql ="CREATE table $table(
         ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY,
         Messages VARCHAR( 50 ) NOT NULL);";
        $stmt = $pdo->exec($sql);
         print("Created $table Table.\n");
    
         $pdo->commit();
    
    } 
    //Our catch block 
    catch(Exception $e){
    
        //Print out the error message.
        echo $e->getMessage(); 
    
        //Rollback the transaction.
        $pdo->rollBack();
    }
    

    提前致谢。

2 个答案:

答案 0 :(得分:1)

由于您的表名包含特殊字符+,因此您需要将其放在反引号中以引用它。

$sql ="CREATE table `$table` (
 ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY,
 Messages VARCHAR( 50 ) NOT NULL);";

每当您在其他查询中使用它时,您都需要记住在表名周围添加反引号。如果您坚持使用这样的每个用户表,您可能希望使用不同的字符来连接它们,例如下划线。

答案 1 :(得分:0)

在转换中创建表在MySQL中不起作用:

在事务中发出诸如DROP TABLE或CREATE TABLE之类的数据库定义语言(DDL)语句时,包括MySQL在内的某些数据库会自动发出隐式COMMIT。隐式COMMIT将阻止您回滚事务边界内的任何其他更改。 来源:https://www.php.net/manual/en/pdo.begintransaction.php