我已经制作了一个表格,我可以在其中输入记录到数据库中。但即使我在其中输入任何内容并点击“提交”,表单也会输入记录。
这是我的代码:
$sql = "INSERT INTO blog_posts (title, body) VALUES ('$post_title', '$post_body')";
if(mysqli_query($link, $sql)){
echo '<p class="sucessful">Post Added Successfully.</p>';
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
那么在提交之前是否可以要求填写表格?如果在表格未填写时提交,则显示错误?
答案 0 :(得分:2)
您可以使用
<?php
$errors = array();
if(empty($post_title)) {
$errors[] = "Post Title is empty";
} else if(empty($post_body)) {
$errors[] = "Post Body is empty";
}
if(!empty($errors)) {
$sql = "INSERT INTO blog_posts (title, body) VALUES ('$post_title', '$post_body')";
if(mysqli_query($link, $sql)){
$errors[] = '<p class="sucessful">Post Added Successfully.</p>';
} else{
$errors[] = "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
if(!empty($mysqlErrors)) {
foreach($mysqlErrors as $error) {
echo $error."<br/>";
}
}
} else {
foreach($errors as $error) {
echo $error."<br/>";
}
}
?>