PHP表单插入数据库,检查没有输入

时间:2017-11-10 05:34:36

标签: php required

我的问题是,当用户没有在表单中输入字段时,如何让表单显示错误。当他们根本没有填写表格并且只是点击输入时我可以让它工作,但是如果他们只填写几个字段就无法使它工作。他们可以填写标题字段和运行时字段,并且可以提交它。如何确保每个字段都填写完整?

<?php
$databaseName = 'movie_database';
$databaseUser = 'root';
$databasePassword = 'root';
$databaseHost = '127.0.0.1';

$conn = new mysqli($databaseHost, $databaseUser, $databasePassword, $databaseName);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo "Connected successfully";

if(isset($_POST['submit'])) {
$value = mysqli_real_escape_string($conn,$_POST['title']);
$value2 = mysqli_real_escape_string($conn,$_POST['rating']);
$value3 = mysqli_real_escape_string($conn,(int)$_POST['Runtime']);
$value4 = mysqli_real_escape_string($conn,(float)$_POST['movie_rating']);
$value5 = mysqli_real_escape_string($conn,$_POST['release_date']);
// Checks for empty fields 
if (empty($value) && empty($value2) && empty($value3) && empty($value4) && empty($value5)) {
    echo 'Please correct the fields';
    return false;
}
// Concatenate the $values into the string
$sql = "INSERT INTO movies(title,rating,Runtime,movie_rating,release_date) 
	VALUES('$value','$value2','$value3','$value4','$value5')";

if ($conn->query($sql)) {
    $msg = "New record created successfully";
} else {
    $msg = "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
}
?>
<form method="post"/>
<p>Enter Movie Title: <input type="text" name="title"/></p> 
<p>Enter Movie Rating(G,PG,PG-13,R): <input type="text" name="rating"/></p> 
<p>Enter Movie Runtime in minutes: <input type="text" name="Runtime"/></p> 
<p>Enter IMDB Movie Rating(0-10.0): <input type="text" name="movie_rating"/></p> 
<p>Enter Movie Release date(YYYY-MM-DD): <input type="text" name="release_date"/></p>  
<button type="submit" name="submit">Submit</button
</form> 

<?php 
if (isset($msg)) {
	echo $msg;
}
?>

2 个答案:

答案 0 :(得分:1)

从正面可以为每个输入添加required属性。所以在每个输入字段中添加它,如: <input type="text" name="title" required/>

从后端(使用PHP)如果您想要填写所有值,请在您的情况下使用&&更改||

// Checks for empty fields 
if (empty($value) || empty($value2) || empty($value3) || empty($value4) || empty($value5)) {
    echo 'Please correct the fields';
    return false;
}

答案 1 :(得分:0)

if (empty($value) && empty($value2) && empty($value3) && empty($value4) && empty($value5)) {
    echo 'Please correct the fields';
    return false;
}

这应该是'或'