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
You are executing the $conn->query($sql) twice. The first one is in $result = $conn->query($sql);
and the second if ($conn->query($sql) === TRUE)
. That is why you get 2 entries in the for one request.
First check for the user you are prepering to insert and if it returns 0 statements then go with the second if
you have wrote.
Edit 2:
Try use PDO:
The code will look something like this:
if( isset( $_POST["submit"] ) ) {
$stmt = $pdo->prepare("SELECT username FROM users WHERE username LIKE ?");
$stmt->execute( array( $_POST["username"] ) );
$_results = $stmt->get_result();
if( count( $_results ) > 0 ) {
die("Error, please consult an admin!");
} else {
$stmt = $pdo->prepare('INSERT INTO users (username) VALUES( ? )' );
$stmt->bindParam( 1, $_POST['username'] );
if( $stmt->execute() ) {
echo 'Success';
} else {
echo 'Whoops, you have an error mate!';
}
}
}
Hope it helps
Try this 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 IGNORE 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!");
}
}
echo "New record created successfully";
}else {
die("Error, please consult an admin: " . $sql . "<br>" . $conn->error);
}
$conn->close();