php - How to save field form in database with required fields

987

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>
169

Answer

Solution:

In theaction="" 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 thisaction="file.php"

to check whether an input is correctly filled, you have many ways of doing so :

`<input type="text" name="name" value="<?php echo $name;?>" required>` 

(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!

People are also looking for solutions to the problem: mysql - PHP - getting the first sum number only

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.