您好,我有以下 PDO 插入数据库函数,我如何检查数据库内是否已存在这样的记录,从而给出用户已使用此信息注册的错误?我的 table 就是这样组织的
id | curso_id | user_id
1 | 12 | 43
2 | 5 | 56
因此,如果数据库中存在 curso_id = 12 和 user_id = 43 的组合,请不要注册第二个此类组合,否则会出现错误。
$userid = $_SESSION['userID'];
$cursoid = $_GET["id"];
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); //our new PDO Object
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare( "Insert Into subscriptions ( curso_id, user_id ) Values ('$cursoid', '$userid')" );
$stmt->execute();
} catch (PDOException $e) {
echo "I'm sorry there is a problem with your operation.."; $e->getMessage(); //catch and show the error
}
$con = null;
header( 'Location: cursos.php' ) ;
}
感谢您提前提供帮助
最佳答案
设置一个唯一索引:unique( curso_id, user_id )
约束。
然后您可以使用类似这样的查询和 ON DUPLICATE KEY UPDATE
子句:
INSERT INTO subscriptions
( curso_id, user_id )
VALUES
('12', '43')
ON DUPLICATE KEY UPDATE user_id = user_id;
如果 affected-rows
为 1
,则插入新行。
如果 affected-rows
为 2
,则更新现有行。
根据受影响的行值,您可以选择向用户显示适当的消息。
...
INSERT ... ON DUPLICATE KEY UPDATE
REPLACE
Insert to table or update if exists (MySQL)
关于php - PDO INSERT不在mysql中注册重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19203665/