Im trying to making sure than when an user introduce a username in a form, that username is not already in my Database.
When I introduce a username that already exist, I get the error message: "* Username already exist". However, the username it is introduce in the database and therefore I have duplication in my database.
Also, anytime I update(F5) the browser a NULL record gets introduce in my database.
THANK YOU SO MUCH!!! :)
Below is the code I'm using:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$usernameErr = "";
$username = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "Username is required";
} else {
$username = test_input($_POST["username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z0-9 ]*$/",$username)) {
$usernameErr = "Only letters, numbers and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
if ($usernameErr == '')
{
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$username = pg_escape_string($_POST['username']);
$query = "SELECT username FROM host";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
if ($username == $myrow[username]) {$usernameErr = "Username already exist";}
else { $query = "INSERT INTO host(username) VALUES('" . $username . "')";}
printf ("$myrow[username]>");
}
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
$username = "";
pg_close();
}
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="username" placeholder="User Name" value="<?php echo $username;?>">
<span class="error">* <?php echo $usernameErr;?></span>
<br><br>
<input type="submit" name="submit" value="SAVE">
</form>
</body>
</html>