有没有办法阻止表单在php上抛出ctype_digit错误后提交
问题描述:
im a newbie here in php still learning. what im in need of is to stop the form once the user put something other than an integer in the Age field and not submit to mysql. here is my the basic form and code:
add.html->
<form action="add.php" method="post" name="form1">
<table width="25%" border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Add"></td>
</tr>
</table>
</form>
And here is the process file add.php->
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
//including the database connection file
include_once("config.php");
if(isset($_POST['Submit'])) {
$name = mysqli_real_escape_string($mysqli, $_POST['name']);
$age = mysqli_real_escape_string($mysqli, $_POST['age']);
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// checking integer fields
if (!ctype_digit($age)){
echo "<font color='red'>ERREUR! age n'est PAS entier</font><br/>";
}
// checking empty fields
if(empty($name) || empty($age) || empty($email)) {
if(empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if(empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
//link to the previous page
echo "<br/><a href='javascript:self.history.back();'>Go Back</a>";
} else {
// if all the fields are filled (not empty)
//insert data to database
$result = mysqli_query($mysqli, "INSERT INTO users(name,age,email) VALUES('$name','$age','$email')") or die(mysql_error());
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
Please ive read many posts but as a beginner it seems too difficult to dive into javascript now. if this is the only solution can you teach me -lol- how to implement the few lines of scripts. thanks
答
You can use exit function (http://php.net/manual/en/function.exit.php)
if (!ctype_digit($age)){
echo "<font color='red'>ERREUR! age n'est PAS entier</font><br/>";
exit();
...
Then the script exectuion will stop at this point.