这个简单的验证问题让我有点发疯!我将它与我一直在学习的一堆其他示例进行比较,但我就是无法理解...
我试图让程序返回简单的消息“请填写所有字段”。如果用户在提交时将任何字段留空。它永远不会得到那个代码。我还有其他类似的例子,所以它一定是我想念的非常简单的东西。谁能告诉我为什么在'if(!empty ...)块之后我没有得到那个'else'语句?
<?php
//PHPAcademy.org Tutorial on PDO
$config['db'] = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'andrew',
'dbname' => 'a_database'
);
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
if (isset($_POST['food']) && isset($_POST['calories']) && isset($_POST['healthy_unhealthy'])) {
$food = $_POST['food'];
$calories = $_POST['calories'];
$healthy_unhealthy = $_POST['healthy_unhealthy'];
echo $food . $calories . $healthy_unhealthy;
if (!empty($food) && !empty($calories) && !empty($healthy_unhealthy)) {
$query = $db->prepare("INSERT INTO food (food, calories, healthy_unhealthy) VALUES (:food, :calories, :healthy)");
$query->bindValue(':food', $food);
$query->bindValue(':calories', $calories);
$query->bindValue(':healthy', $healthy_unhealthy);
if ($query->execute()) {
echo '<br /><strong>Record Added!</strong><br />';
} else {
echo '<br />Oh no, there was a problem!<br />';
}
} else {
echo 'Please complete all fields.';
}
}
?>
<form action="connect.php" method="POST">
Food Type: <br />
<input type="text" name="food"/><br /><br />
Calories: <br />
<input type="number" min="0" name="calories"/><br /><br />
Healthy/Unhealthy? <br />
<input type="radio" name="healthy_unhealthy" value="h"/>Healthy<br />
<input type="radio" name="healthy_unhealthy" value="u"/>Unhealthy<br /><br />
<input type="submit" value="Submit" />
</form>
我认为这与 isset 也检查空值这一事实有关,但在下面的示例中,它一切正常,我看不出有什么区别......
<?php
// Pilot Name, Currency Name, Currency Date, Interval (minutes)
if (isset($_POST['pilot']) && isset($_POST['currency']) && isset($_POST['last_date']) &&
isset($_POST['interval'])) {
$pilot = $_POST['pilot'];
$currency = $_POST['currency'];
$last_date = strtotime($_POST['last_date']);
$interval = $_POST['interval'];
if (!empty($pilot) && !empty($currency) && !empty($last_date) &&
!empty($interval)) {
echo 'Hello <strong>' . $pilot . '</strong>, your ' . $currency . ' is due on ' . date('d-m-y', $last_date + ($interval * 24 * 60 * 60)) .
'<br />';
echo 'Your last currency was ' . date('d-m-Y', $last_date) . '<br /><br />';
} else {
echo 'Please complete all fields.';
}
}
?>
<form action="currency.php" method="POST">
Enter your name:<br />
<input type="text" name="pilot"/><br/>
Enter the last date of your currency (dd-mm-yy):<br />
<input type="date" name="last_date"/></br/>
Enter the currency type:<br />
<input type="text" name="currency"/><br/>
Enter the currency interval in days: <br />
<input type="text" name="interval"/><br/>
<input type="submit" value="submit">
</form>
感谢您的任何建议...