Skip to content

Instantly share code, notes, and snippets.

@TheDefinitionist
Last active December 2, 2016 14:08
Show Gist options
  • Save TheDefinitionist/b02b78f311e59917fe0da7dd7c176620 to your computer and use it in GitHub Desktop.
Save TheDefinitionist/b02b78f311e59917fe0da7dd7c176620 to your computer and use it in GitHub Desktop.
Checks if user already exists. If not, it inserts the user only one time.
<?php
try {
$con = new PDO("mysql:host=localhost;","root","");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$username = "John Doe";
$password = "abc123";
// CREATE
$con->exec("
CREATE DATABASE IF NOT EXISTS registered_users;
USE registered_users;
CREATE TABLE IF NOT EXISTS users (
username VARCHAR(31) NOT NULL,
password VARCHAR(31) NOT NULL
);
");
// INSERT IF NOT EXISTS
$stmt = $con->prepare("
INSERT INTO users (
username, password
)
SELECT * FROM (
SELECT :username,
:password
)
AS compare
WHERE NOT EXISTS (
SELECT username
FROM users
WHERE username = :username
AND password = :password
) LIMIT 1;
");
$taken = $stmt->rowCount();
$stmt->bindParam(":username", $username);
$stmt->bindParam(":password", $password);
if ($stmt->execute()) {
$pfx = "<p>Username <strong>".$username."</strong> ";
if ($stmt->rowCount() == $taken) {
echo $pfx."is taken.</p>";
} else {
echo $pfx."was added.</p>";
}
}
// SELECT
$show = $con->prepare("
SELECT * FROM users
");
if ($show->execute()) {
$result = $show->setFetchMode(PDO::FETCH_OBJ);
foreach($show->fetchAll() as $data) {
echo $data->username." | ".$data->password."<br>";
}
}
// DELETE
$del = $con->prepare("
DELETE FROM users
");
/*if ($del->execute()) {
echo "Table has been cleared.";
}*/
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$con = null;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment