What I'm trying to do is make a username (just username) get sent to a MySQL database, if it isn't already there.
Basically, I'm getting the input, checking it against all other rows in my username
column, and, if the input is not the same as any of them, then add the input to the database. Here is my code:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if( isset( $_POST["submit"] ) ) {
$sql="INSERT INTO users (username)
VALUES('$_POST[username]')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["username"] == $_POST[username]) {
die("Username is already in use!");
}
}
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
}
$conn->close();
No error is reported, but it simply creates the data twice, and doesn't check the input. I can't see how. This is how I've tried. It looks logical that is should work, but it's not. Why?
I'm using MySqli Object-Orientated