How to direct to the same page if the key is the same and direct to another page if it is no duplicate in php?

I do not know how to direct to the same page, in personal.php if the user entered the same FirstName, MiddleName, LastName, and LastSchoolAttended. My current happenings in my code is that, the page is directing to exam.php even though there is the same record, but the record is not adding in the database. So, I want to create an error or design that the user will know if they entered the same entries.

This is my personal.php

 <form action = "exam.php" method = "POST">
    	<tr>
    		<td> <h3> First Name: </td>
    			<td> <input type = "text" name = "FirstName" placeholder = "First Name" maxlength = "40" autofocus required> </h3>	 </td>
    				</tr>

    <tr>
    	<td> <h3> Middle Name: </td> 
    		<td> <input type = "text" name = "MiddleName" placeholder = "Middle Name" maxlength = "40" required> </h3> </td>
    				</tr>
    <tr>
    	<td> <h3> Last Name: </td>
    		<td> <input type = "text" name = "LastName"  placeholder = "Last Name" maxlength = "40" required></h3> </td>
    			</tr>

    <tr>
    	<td> <h3> Age: </td> 
    		<td> <input type = "number" name = "Age"  value = "" placeholder = "Age" maxlength = "2" min = "16" required></h3> </td> 
    			</tr>
    <tr> 
    	<td> <h3> Home Address: </td> 
    		<td> <input type = "text" name = "HomeAddress"  placeholder = "Barangay / Street / Province / City" maxlength = "60" required></h3> </td>
    			</tr>
    <tr>
    	<td> <h3> Contact Number: </td>
    		<td> <input type = "tel" name = "ContactNumber"  placeholder = "Ex. 9123456789 / 123-456-7" maxlength = "10" required></h3> </td>
    			</tr>

    <tr>
    				<td> <h3> Last School Attended: </td>
    				<td>  <input type = "text" name = "LastSchoolAttended"  placeholder = "Last School Attended" maxlength = "60" required> </h3> </td>
    			</tr>

    </table>
    </form>

This is my exam.php

<?php
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // Turn on mysqli exeptions. Much better than errors.
    $conn = new mysqli('localhost', 'root', "", 'studentsinformation'); //Initialize Db connection

$FirstName = $_POST['FirstName'];
$MiddleName = $_POST['MiddleName'];
$LastName = $_POST['LastName'];
$Age = $_POST['Age'];
$HomeAddress = $_POST['HomeAddress'];
$ContactNumber = $_POST['ContactNumber'];
$LastSchoolAttended = $_POST ['LastSchoolAttended'];

This is my query.
$sql = "SELECT * FROM personal where FirstName = '$FirstName' And MiddleName = '$MiddleName' And LastName = '$LastName' And LastSchoolAttended = '$LastSchoolAttended';

To keep things simple you should handle your form on the same page as where you show your form. Because of this reason you could simply remove the whole action attribute in the form element.
<form method="POST">
Now take a look to this example:

function validate($naam, $email)
{
    $errors = array();
    
    // constraints for name
    if(strlen($name) < 2)
        $errors['name'] = 'You must enter a name.';
    
    // contraints for email
    if(!strlen($email))
        $errors['email'] = 'You must enter your email.';
    else if(!filter_var($email, FILTER_VALIDATE_EMAIL))
        $errors['email'] = 'This is not an valid email.';
    
    // return an array with error messages
    return $errors;
}

// initialization
$name = '';
$email = '';
$errors = array();

// when the form is sent
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // overwrite the defautvalues for the values out of the $_POST array
    $name = $_POST['name'];
    $email = $_POST['email'];

    // validate the post data
    $errors = validate($_POST['name'], $_POST['email']);
    
    // if there were no errors
    if(!count($errors))
    {
        /* 
         * handle your form e.g. send an email or store data to the database
         */
        
        // redirect the user (to leave the POST method)
        header('Location: confirmation.html');
        exit;
    }
}
?>
<!doctype html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>My first form</title>
    </head>
    <body>
        <?php
            if(count($errors)) {
                echo '<ul id="errors">';
                foreach($errors as $error) {
                    echo '<li>' . $error . '</li>';
                }
                echo '</ul>';
            }
        ?>
        <form method="post">
            <input type="text" name="name" value="<?php echo $name ?>">
            <input type="email" name="email" value="<?php echo $email ?>">
            <button type="submit">Verzenden</button>
        </form>
    </body>
</html>```

So, should I just remove the action bar and then just cut my <?php in exam.php and paste it in my personal.php?

Yes i would do that. The idea is that you can add validation errors on a simple manner.
By the way you should use div’s instead of table cells but well first things first not?

I tried it but I am having too many errors. :frowning: I am having an error with the bind param. This is my recent code: If I uncomment the echo, the errors is showing also, the record is not fetching to my admin-page

    <?php
    	mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); 
    $conn = new mysqli('localhost', 'root', "", 'studentsinformation'); 

    $FirstName = '';
    $MiddleName = '';
    $LastName = '';
    $Age = '';
    $HomeAddress = '';
    $ContactNumber = '';
    $LastSchoolAttended = '';
    $Strand = '';
    $SchoolAddress = '';
    $Adviser = '';
    $Honor1 = '';
    $Honor2 = '';
    $Honor3 = '';
    $Honor4 = '';
    $Father = '';
    $EducationalFather = '';
    $Mother = '';
    $EducationalMother = '';
    $Guardian = '';
    $Occupation = '';
    $ExamineeID;

    if (isset($_POST['submit'])) {

    $FirstName = $_POST['FirstName'];
    $MiddleName = $_POST['MiddleName'];
    $LastName = $_POST['LastName'];
    $Age = $_POST['Age'];
    $HomeAddress = $_POST['HomeAddress'];
    $ContactNumber = $_POST['ContactNumber'];
    $LastSchoolAttended = $_POST ['LastSchoolAttended'];
    $Strand = $_POST ['Strand'];
    $SchoolAddress = $_POST ['SchoolAddress'];
    $Adviser = $_POST ['Adviser'];
    $Honor1 = $_POST ['Honor1'];
    $Honor2 = $_POST ['Honor2'];
    $Honor3 = $_POST ['Honor3'];
    $Honor4 = $_POST ['Honor4'];
    $Father = $_POST ['Father'];
    $EducationalFather = $_POST ['EducationalFather'];
    $Mother = $_POST ['Mother'];
    $EducationalMother = $_POST ['EducationalMother'];
    $Guardian = $_POST ['Guardian'];
    $Occupation = $_POST ['Occupation'];
    $ExamineeID;

    //$sql = "SELECT  ExamineeID, FirstName, MiddleName, LastName, LastSchoolAttended From personal Where FirstName = '$FirstName' And MiddleName = '$MiddleName' And LastName = '$LastName' And LastSchoolAttended = '$LastSchoolAttended' LIMIT 1";
    $sql = "SELECT ExamineeID, FirstName, MiddleName, LastName, LastSchoolAttended From personal Where FirstName = ? And MiddleName = ? And LastName = ? And LastSchoolAttended = ? LIMIT 1";
    //$sql = "SELECT * FROM personal WHERE  FirstName = '$FirstName' And MiddleName = '$MiddleName' And LastName = '$LastName' And LastSchoolAttended = '$LastSchoolAttended' LIMIT 1";

  



    $res = mysqli_query($conn, $sql);

    if (mysqli_num_rows($res) > 0) {

    	$stmt = $conn->prepare($sql); 
    	$stmt->bind_param("ssss", $FirstName,$MiddleName,$LastName,$LastSchoolAttended);
    	$stmt->execute();
    	$stmt->bind_result($FirstName,$MiddleName,$LastName,$LastSchoolAttended);
    	$stmt->store_result(); 
    	$stmt->fetch();
    	$stmt->close();
    	//echo  "Sorry... You already took the exam";  
    header("location:dummy.php");
    	//$name_error = "Hi";
    }
    else {

    if (!isset($ExamineeID)) {  
      $INSERTpersonal = "INSERT INTO personal (FirstName, MiddleName, LastName, Age, HomeAddress, ContactNumber, LastSchoolAttended, Strand, SchoolAddress, Adviser) values (?,?,?,?,?,?,?,?,?,?)";
      $stmt = $conn->prepare($INSERTpersonal);
      $stmt->bind_param("sssisissss", $FirstName,$MiddleName,$LastName,$Age,$HomeAddress,$ContactNumber,$LastSchoolAttended,$Strand, $SchoolAddress,$Adviser);
      $stmt->execute();
      $stmt->close();

      
      $stmt = $conn->prepare($sql);
      $stmt->bind_param("ssss", $FirstName,$MiddleName,$LastName,$LastSchoolAttended);
      $stmt->execute();
      $stmt->bind_result($ExamineeID,$FirstName,$MiddleName,$LastName,$LastSchoolAttended);
      $stmt->store_result();
      $stmt->fetch();
      $stmt->close();
    }
   }
    header("location:exam.php");
    }
}

?>

The posted code contains an extra }, so, either this code produces a php syntax error and doesn’t run at all or that’s not all the relevant code. Ignoring that problem, the current $sql query statement is for a prepared query, but you are executing it as a non-prepared query. This produces an sql syntax error and the code doesn’t run past that point. If you have code that you need help with, you need to post the actual code.

Next, don’t write out line after line of code for every form field/variable. This is just a waste of your time. Instead, operate on the submitted form data as a set, by keeping it as an array and operating on the elements of the array. This will simplify the current code and will lead to a more advanced programming method of dynamically processing the form data.

One of your previous threads for this problem - Composite Keys in PHP concerned using a composite key. By defining an appropriate composite unique key/index for the fields in this table, you would just attempt to insert the data, then detect if a duplicate key error occurred to let you know if the data already exists. Your form processing code should -

  1. Detect that a post method form was submitted.
  2. Trim all the input data at once. This can be done with one single statement.
  3. Validate all the inputs at once, storing validation errors in an array, using the field name as the array index. This array is also an error flag. If the array is empty, there are no errors. You can display the contents of this array at the appropriate point in the html document when you re-display the form.
  4. If there are no errors, use the submitted form data. You would only produce and execute the INSERT query. Since you are already using exceptions for errors, you would have a try/catch block for the execution of the query, detect if the error number is for a duplicate key, then setup an error message for the user (add it to the array holding the error messages) telling them that the submitted data already exists. If the error number is not for a duplicate key, you would re-throw the exception and let php handle it.

Lastly, if you use the much simpler PDO extension, about half of the database statements will disappear. The only header() redirect you should have is after the end of successfully processing the form data, to redirect to the exact same url of the page, to cause a get request. Also, every header() redirect needs an exit statement to stop program execution.

Can I post the whole code of my personal.php? So you can know, what is the error of my syntax?

Sponsor our Newsletter | Privacy Policy | Terms of Service