【问题标题】:Create Table In PDO Transaction在 PDO 事务中创建表
【发布时间】:2017-07-13 21:42:01
【问题描述】:

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

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

步骤

  1. 在数据库中查找聊天状态为 0 的用户
  2. 将用户添加到数据库中(使用预先确定的变量)
  3. 将状态为 0 的用户和插入的用户的聊天状态从 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();
}

提前致谢。

【问题讨论】:

  • 为每个用户创建单独的表是可怕的数据库设计。动态信息应该在单元格内容中,而不是表格或列名。
  • 您要为每个用户创建一个表?这似乎是个糟糕的主意。
  • hmm 有趣.. 我会考虑重做设计以将设计输入到单元格内容中。感谢@Barmar 的反馈
  • 你也没有检查运行时应该得到的错误

标签: php mysql pdo


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    在事务中创建表在 MySQL 中不起作用:

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

    【讨论】:

      猜你喜欢
      • 2012-01-06
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 2012-04-26
      • 2013-03-25
      • 1970-01-01
      相关资源
      最近更新 更多