I'am tryng to show a message after you pressed submit with information.
1. This name allready exists, use another
or
2. The name is added!
html
<form action="add.php" method="post">
<input type="text" name="name" id="name" class="form-control" required>
<input class="btn btn-default" type="submit" value="Submit">
</form>
php
$connectie=mysqli_connect("localhost","usernam","pw","db");
$name = $_POST['name'];
$name = stripslashes($name);
$name = mysql_real_escape_string($name);
$check_if_exists="SELECT * FROM names WHERE name = '$name'";
if($data[0] > 1) {
echo"already exists";
} else {
$newUser="INSERT INTO users (name) values('$name')";
if (mysqli_query($connectie,$newUser))
{
echo "name is registerd";
}
else
{
echo "error<br/>";
}
Right now it post the echo on add.php, not on the page where the form is. How do I get it there?
You can use session / sessionflashdata.
First, you are not running the select query properly. It should have been:
$check_if_exists="SELECT * FROM names WHERE name = '$name'";
$count = mysql_num_rows($check_if_exists);
if($count != 0) { // this means that the name already exists:
$_SESSION['msg']="The name already exists. Please try another name";
} else {
//perform the insert query and have the session msg
$_SESSION['msg']="The name was inserted successfully";
}
header('Location: form.php');
// Now in your form page just above the form, have a div to display this message as:
<div class="msg">
<?php if(isset($_SESSION['msg']))
{
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
</div>
NOTE: you must start the session on both the pages. Have this code on top of both the pages
<?php
session_start();
?>
</div>
You should consider using a session for this. Add session_start()
to the top of both of your files.
if(mysqli_query($connectie, $uewUser))
{
$_SESSION['flash'] = 'name is registered';
}
else
{
$_SESSION['flash'] = 'error<br/>';
}
Then in your page with the form, perform the following check wherever you want to print the data.
if(isset($_SESSION['flash']))
{
echo $_SESSION['flash'];
unset($_SESSION['flash']);
}
This will make sure that the session message is preserved only for the next request.