From 9495736a633f759ec30edd099a1223378a2aadb8 Mon Sep 17 00:00:00 2001 From: bots002 Date: Mon, 6 Nov 2017 08:27:40 +0700 Subject: [PATCH 1/2] 1st pull --- add.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/add.php b/add.php index 8f21db0..d306ef2 100644 --- a/add.php +++ b/add.php @@ -41,6 +41,9 @@ echo "
View Result"; } } + + + ?> From a1e510959d0f8d38fa258b6de6c6750082a61bb9 Mon Sep 17 00:00:00 2001 From: bots002 Date: Mon, 6 Nov 2017 08:43:21 +0700 Subject: [PATCH 2/2] revision add.php --- add.php | 47 ++++++++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/add.php b/add.php index d306ef2..a6a9712 100644 --- a/add.php +++ b/add.php @@ -9,32 +9,24 @@ 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']); - + + unset($_POST['Submit']); + //escape string function + $_POST = escapeStringArr($_POST); + // checking empty fields - if(empty($name) || empty($age) || empty($email)) { - - if(empty($name)) { - echo "Name field is empty.
"; - } - - if(empty($age)) { - echo "Age field is empty.
"; - } - - if(empty($email)) { - echo "Email field is empty.
"; - } - + $validateStatus = validatePost($_POST); + if($validateStatus['isValid']) { //if having empty fields + //print error text + echo $validateStatus['err']; //link to the previous page echo "
Go Back"; } 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')"); + $sql = "INSERT INTO users (`".implode("`, `" , array_keys($_POST))."`) VALUES ('".implode("', '" , $_POST)."')"; + $result = mysqli_query($mysqli, $sql); //display success message echo "Data added successfully."; @@ -42,7 +34,24 @@ } } +function escapeStringArr($postArr){ + foreach ($postArr as $key => $value) { + $postArr[$key] = mysqli_real_escape_string($mysqli, $value); + } + return $postArr; +} +function validatePost($postArr){ + $err = ""; + $isValid = true; + foreach ($postArr as $key => $value) { + if(empty($value)){ + $err = $err."".$key." field is empty.
"; + $isValid = false; + } + } + return array('err' => $err , 'isValid' => $isValid); +} ?>