PHP - detect mysql update/insertion failure due to violated unique constraint

前端 未结 7 1309
无人及你
无人及你 2020-11-30 11:10

This is kind of similar to this question:

PHP MySQL INSERT fails due to unique constraint

but I have a different twist. Let\'s say I have a table with only

7条回答
  •  没有蜡笔的小新
    2020-11-30 12:04

    If you know some SQL, try this solution (tested)

    $username = "John";
    $stmt = $pdo->prepare("
        INSERT INTO users (
            username
        ) SELECT * FROM (
            SELECT :username
        ) AS compare
        WHERE NOT EXISTS (
            SELECT username 
            FROM users 
            WHERE username = :username
        ) LIMIT 1;
    ");
    $stmt->bindParam(":username", $username);
    if ($stmt->execute()) {
        if ($stmt->rowCount() == 0) {
            echo "Dublicate Username, ".$username." already exists.";
        } else {
            echo $username." not in use yet.";
        }
    }
    

提交回复
热议问题