Last active
December 2, 2016 14:08
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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