jeudi 2 avril 2015

Unexpected result php if statements

When I submit an empty form the success message is displayed and am not sure why. It shouldn't pass the first if statement if anything is left blank, why is it displaying this?


I previously had the if statement use variables but then changed them because of undefined index errors. A form with any missing fields should display the error message shown in the code


php:



<?php
require_once 'db/connect.php';
$error='';
$success='';

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

if ( (isset($_POST['Forename'])) && (isset($_POST['Surname'])) && (isset($_POST['Gender'])) && (isset($_POST['YearGroup'])) ) {
/*print_r($_POST);*/

$forename = $_POST['Forename'];
$surname = $_POST['Surname'];
$gender = $_POST['Gender'];
$yeargroup = $_POST['YearGroup'];

//To protect MySQL injection
$forename= stripslashes($forename);
$surname = stripslashes($surname);
$forename = mysqli_real_escape_string($con, $forename);
$surname = mysqli_real_escape_string($con, $surname);

if ($teacher_form = $con->query("SELECT Form FROM teacher WHERE Username = '" . $_SESSION['Username'] . "'")) {
$row1 = $teacher_form->fetch_assoc();
$form = $row1['Form'];
$con->query("INSERT INTO student (Forename, Surname, Gender, Year_group, Form) VALUES (\"" . $forename ."\", \"" . $surname . "\", \"" . $gender . "\", " . $yeargroup . ", \"" . $form . "\") ");
$success = 'Student has been successfully added to the database';
}
}

else {
$error='All fields must be completed';
}
}
?>


HTML form:



<?php
session_start();
require_once 'db/checkuserloggedin.php';
include 'db/header.php';
include 'addstudent.php';
?>

<!DOCTYPE html>
<html>
<head>
<title>Add students</title>
</head>

<body>

<div id="logoutbutton">
<button class="btn" onclick="location.href='logout.php'">Logout</button>'
</div>

<link rel="stylesheet" type="text/css" href="styles.css">
<?php echo "<form method =\"POST\">"; ?>
<h3> Add student </h3>
<table>
<tr>
<td>Forename</td>
<td><input type="text" name="Forename"></td>
</tr>

<tr>
<td>Surname</td>
<td><input type="text" name="Surname"></td>
</tr>

<tr>
<td>Gender</td>
<td><select name ="Gender">
<option value="" style="display:none;"></option>
<option> M </option>
<option> F </option>
</select> <br>
</td>
</tr>

<tr>
<td>Year group</td>
<td><select name ="YearGroup">
<option value="" style="display:none;"></option>
<option> 7 </option>
<option> 8 </option>
<option> 9 </option>
<option> 10 </option>
</select> <br>
</tr>
</table>

<input type="submit" name="submit" value ="Add">
<input type="reset" value ="Reset"> <br>
<span class="error"><?php echo $error;?></span>
<span class="error"><?php echo $success;?></span>
<?php echo "</form>"; ?>
</body>
</html>

Aucun commentaire:

Enregistrer un commentaire