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
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.";
}
}