In this form, user needs to insert three things- 'Make' , 'Year' and 'Mileage'. First one has to be string, and the other two must be integers. If not then it will show error. The problem is with the last two. But if user inputs 'Year' as a string, and 'Mileage' as integer (or vice-versa), it does NOT show any error. Then I checked the database,and found that that string value gets changed to 0 (zero) automatically. May be that is the reason for the failure in validation.
Here is the code:
<?php
if ( ! isset($_GET['name']) || strlen($_GET['name']) < 1 ) {
die("Name parameter missing");
}
if ( isset($_POST['logout']) ) {
header('Location: index.php');
return;
}
?>
<?php
require_once "pdo.php";
$failure = false;
$success = true;
if ( isset($_POST['make']) && isset($_POST['year']) && isset($_POST['mileage']) ) {
if (strlen($_POST['make']) < 1) {
$failure = "Make is required";
}
else if( !is_numeric($_POST['year']) && !is_numeric($_POST['mileage']) ) {
$failure = "Mileage and year must be numeric";
}
else {
$stmt = $pdo->prepare('INSERT INTO autos
(make, year, mileage) VALUES ( :mk, :yr, :mi)');
$stmt->execute(array(
':mk' => htmlentities($_POST['make']),
':yr' => htmlentities($_POST['year']),
':mi' => htmlentities($_POST['mileage'])));
$success = "Record inserted";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Kho. Iftekhar Alam</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Tracking Autos for <?php echo $_GET['name']; ?> </h1>
<?php
if ( $failure !== false ) {
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
if ( $success !== true ) {
echo('<p style="color: green;">'.htmlentities($success)."</p>\n");
}
?>
<form method="post">
<p>Make:
<input type="text" name="make" size="60"/></p>
<p>Year:
<input type="text" name="year"/></p>
<p>Mileage:
<input type="text" name="mileage"/></p>
<input type="submit" value="Add">
<input type="submit" name="logout" value="Logout">
</form>
<h2>Automobiles</h2>
<ul>
<?php
$stm = $pdo->query("SELECT make,year,mileage from autos");
while ($row = $stm->fetch(PDO::FETCH_ASSOC)) {
echo "<li>";
echo $row['year'].' '.$row['make'].' '.'/'.' '.$row['mileage'];
echo "</li>";
}
?>
<p>
</ul>
</div>
<script data-cfasync="false" src="/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js"></script></body>
</html>