Kevin Kevin - 4 years ago 115
PHP Question

Getting a message when name exists or added



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?

Answer Source

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();
?>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download