【发布时间】:2017-07-13 21:42:01
【问题描述】:
如何修复此事务,以便 pdo 查询在步骤 #4 中创建一个新表?
前三个步骤有效,但我似乎无法让 #4 工作。
步骤
- 在数据库中查找聊天状态为 0 的用户
- 将用户添加到数据库中(使用预先确定的变量)
- 将状态为 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 的反馈
-
你也没有检查运行时应该得到的错误