What am I doing wrong here? All the data was subitting until I added the last part of the code, the IF(){} statement. I want to make it where if the information was submitted correctly, for it to say THANK YOU!, else, display the error i set.
<form method="POST">
<input type="text" name="username" placeholder="username"><br />
<input type="password" name="password" placeholder="password"><br />
<input type="submit">
</form>
<?php
if(isset($_POST['username'], $_POST['password'])){
require 'core/db.php';
$conn = dbConnect()->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$conn->bindParam(1, $_POST['username']);
$conn->bindParam(2, $_POST['password']);
$conn->execute();
if($conn === true){
echo 'Thanks!';
header('Location: index.php');
exit;
} else{
echo 'something went wrong';
}
}
?>
It's not the $conn
that you should checking for true
against. $conn
is instance of PDOStatement
. You should instead be checking the return value of $conn->execute()
.
if($conn->execute() === true){
header('Location: index.php');
exit;
} else{
echo 'something went wrong';
}
As @mjayt pointed you should not output content before header
call. You could definitely output using output buffering ob_start()...ob_end_flush()
, but I do not assume the echo
is really necessary here.
if($conn->execute()){
header('Location: index.php?success=true');
exit;
} else{
echo 'something went wrong';
}
I would just do this, the echo won't work, it will break the header() redirect because you are sending content to the browser. Even if it did, you wouldn't see it because it will have redirected you to the other page. I usually add a flag to the redirect so I can display a success message there.