php - How to save field form in database with required fields
Hello I'm figuring how to save the field entered into database when there's no field required left.
I can already save from database with php and mysqli, but I don't want to include the null/blank value from the database which is why I'm using required field but I don't know how to use it. What I wanted to do is when all the required field is not null or has already value in it, it will gonna save from the database.
I don't know what to put on form method=post action="HERE"
PS: Sorry for bad english.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span >* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span >* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Answer
Solution:
In the
action=""
you should point to the php file that is gonna do the back-end job. (getting the datas, checking the inputs, and storing into the database).like this
action="file.php"
to check whether an input is correctly filled, you have many ways of doing so :
(html5)
you can do it serverside ( in your php file )
if(!isset($_POST['name'))
ORif(strlen(trim($_POST['name'])) !== 0)
ORif($_POST['name'] !== '')
and many other ways.
Hope this was what you were searching for!