Reputation: 2965
I have a prepared php statement to insert a row into my database. I have (what i consider) error checking along the way. At the end there is a check for an error on $stmt->execute()
. If it returns false
I want it to cancel the INSERT
operation and show my message. The value is false
but the INSERT
is still successful. I had assumed if $stmt->execute()===false
then there would be no INSERT
into my database.
I apologize if this is a duplicate, I was having trouble finding a previous question similar to mine.
Here is the section causing the issue:
$sql = "INSERT INTO login (username, password, name, branch, officer, type, alerts) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $nbadmin->prepare($sql);
if(false===($nbadmin->prepare($sql))){
$nbadmin->close();
echo '<script>alert("Something went wrong; try again.")</script>';
error();
}
$stmt->bind_param('sssssss', $user, $pass, $name, $branch, $officer, $type, $alert);
if(false===($stmt->bind_param('sssssss', $user, $pass, $name, $branch, $officer, $type, $alert))){
$nbadmin->close();
echo '<script>alert("Something went wrong; try again.")</script>';
error();
}
$stmt->execute();
if(false===($stmt->execute())){
$nbadmin->close();
echo '<script>alert("Something went wrong; try again.")</script>';
error();
}else{
$nbadmin->close();
finish();
}
function error(){
header("Refresh: 0; url=../edit-user.php#user-form");
}
Upvotes: 2
Views: 1483
Reputation: 18584
You are executing your query twice.
In fact your code reads:
$stmt->execute();
if(false===($stmt->execute())){
$nbadmin->close();
echo '<script>alert("Something went wrong; try again.")</script>';
error();
}else{
$nbadmin->close();
finish();
}
However, the first row of that fragmen executes the prepared statement, which is then executed again as part of the if(...)
condition.
This so performs another insert, which fails, probably because there is some unique constraint on your database table, I would guess on the username
field.
You have two possible solutions. First, you could save the result of the execute()
into a variable, like this:
$result = $stmt->execute();
if(false === $result) { ... }
Or else you could call the method directly inside the if(...)
statement, like this:
// $stmt->execute(); // remove this line
if(false === $stmt->execute()) { ... }
I myself would favor the first option though.
Finally, please note that you execute also $nbadmin->prepare($sql)
and $stmt->bind_param('sssssss', $user, $pass, $name, $branch, $officer, $type, $alert)
twice, for the same reason, but those do not seem to generate an error.
Upvotes: 3