为什么我的输入验证不能阻止空值?

  • 本文关键字:不能 空值 验证 php mysql
  • 更新时间 :
  • 英文 :


每次当我没有Make、Model或Mileage的值时,我都会收到同样的错误,我不知道如何修复它。如果我插入正确的信息,它会运行良好,但不会显示我的验证。

这是代码。

这是错误。

致命错误:未捕获的PDOException:SQLSTATE[HY000]:常规错误:1366中第1行的列"year"的整数值"不正确C: \MAMP\htdocs\course_2_week2\autos.php:30堆栈跟踪:#0C: \MAMP\htdocs\course_2_week2\autos.php(30(:PDO声明->execute(数组(#1{main}抛出inC:\MAMP\htdocs\course_2_week2\autos.php第30行

<?php 
require_once "pdo.php";
$failure = false;  // If we have no POST data
$failure2 = false;  // If we have no POST data for make
// Demand a GET parameter
if ( ! isset($_GET['email']) || strlen($_GET['email']) < 1  ) {
die('Email parameter missing');
}
if ( isset($_POST['make']) && isset($_POST['year']) && isset($_POST['mileage']) && isset($_POST['add'])) {
$sql = "INSERT INTO autos (make, year, mileage) 
VALUES (:make, :year, :mileage)";
echo("<pre>n".$sql."n</pre>n");
// Validation checks
if ( ! (is_numeric($_POST['mileage']) || is_numeric($_POST['year'])) ) {
$failure = 'Mileage and year must be numeric';
} if ( strlen($_POST['make']) < 1) {
$failure2 = 'Make is required';  // If we have no POST data for make
} 
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':make' => $_POST['make'],
':year' => $_POST['year'],
':mileage' => $_POST['mileage'])
);
} 
// If the user requested logout go back to index.php
if ( isset($_POST['logout']) ) {
header('Location: index.php');
return;
}
$stmt = $pdo->query("SELECT make, year, mileage FROM autos");
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
<?php require_once "bootstrap.php"; ?>
<title>Zaccharie Charvolin's Login Page</title>

</head>
<body>
<div class="container" >

<h2>Please Login</h2>

<form method="post">
<p>Make:
<input type="text" size="40" name="make"></p>
<p>Year:
<input type="text" size="40" name="year"></p>
<p>Mileage:
<input type="text" size="40" name="mileage"></p>
<input type="submit" size="40" value="Add" name="add"></p>
<input type="submit" size="40" name="logout" value="Log out" ></p>
</form>

<h2>Automobiles</h2>

<?php

foreach ($rows as $row) {
echo "<ul><li>";

echo($row['year'].' ');

echo($row['make'].' / ');
echo($row['mileage']);
echo("</li></ul>n");
}
?>

</div>
</body>
</html>```

即使验证失败,您也在执行SQL。您应该检查是否设置了任何故障变量并跳过它。

if (!$failure && !$failure2) {
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':make' => $_POST['make'],
':year' => $_POST['year'],
':mileage' => $_POST['mileage'])
);
}

为了避免有很多$failureX变量,我建议您使用数组而不是单独的变量。然后你可以检查数组是否为空:

if (empty($failures)) {
...
}

最新更新