PHP Display post variables - php

I'm looking for a bit of help and a bit of an explanation here.
I have created an HTML form with several input fields and some very basic PHP validation when POSTing the inputs. My validation just checks to see if the field has data and if not, it prompts the user to enter data in the field by displaying an error. My hope is ultimately to POST these inputs, check them against a database, and if they aren't there, then add them to the database. But, this is not my issue at hand.
Currently, my objective is to take all of the inputs in my field that I want to POST and to display them in a field below my error display area. I had hoped to just echo the data but for some reason, not all of the entered data appears.
Of the 5 entry fields in the code below, 4 are basic input fields and one is a text area. If i enter anything into the basic input fields, only the last input will echo in my display area. If i enter something into field 1 and leave the rest blank, field 1 will display. Also, if I enter something into the text area, it will always display. Finally, my PHP validation does not appear to work with my textarea type input (labeled 'note') and will not return an error if the 'note' input is left blank.Can anyone explain: (1) How do I fix it so that all 5 inputs display in the display div?; (2) Why does this happen?; (3) why is no error returned if the text area (labeled 'note') is left blank?
Thank you.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
//form validation for general entry form
// define variables and set to empty values
$clientErr = $matterErr = $dateErr = $timeErr = $noteErr= "";
$client = $matter = $date = $time = $note = "";
//on post, check to see if variable is empty. if not empty
//parse it and assign value back to variable name
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$complete = true;
$postArray = [];
if (empty($_POST["client"])) {
$clientErr = "*A client name is required. ";
$complete = false;
}else {
$client = test_input($_POST["client"]);
//$postArray[] = $client;
}
if (empty($_POST["matter"])) {
$matterErr = "*A matter name is required. ";
$complete = false;
}else {
$client = test_input($_POST["matter"]);
}
if (empty($_POST["date"])) {
$dateErr = "*A date is required. ";
$complete = false;
}else {
$client = test_input($_POST["date"]);
}
if (empty($_POST["time"])) {
$timeErr = "*A time entry is required. ";
$complete = false;
}else {
$client = test_input($_POST["time"]);
}
if (empty($_POST["note"])) {
$noteErr = "*A note is required. ";
$complete = false;
} else {
$note = test_input($_POST["note"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<label for="client">Client:</label>
<input type="text" placeholder = "Enter Client Name" name="client"> *
<label for="matter">Matter:</label>
<input type="text" placeholder = "Enter Matter Name" name="matter"> *
<label for="date">Date:</label>
<input type="text" placeholder = "Enter Date" name="date"> *
<label for="time">Time:</label>
<input type="text" placeholder ="Time to nearest tenth hour" name="time"> *
<label for="note">Note:</label>
<textarea name="note" placeholder ="Enter Any Notes" rows="4" cols="40"></textarea>
<input type="submit" name="submit" value="Submit" class="submitbutton">
</form>
<div class="errorDiv">
<?php
echo $clientErr;
echo $matterErr;
echo $dateErr;
echo $timeErr;
?>
</div>
<div class ="displayDiv">
<?php
echo "<h2>Your Input:</h2>";
echo $client;
echo "<br>";
echo $matter;
echo "<br>";
echo $date;
echo "<br>";
echo $time;
echo "<br>";
echo $note;
?>
</div>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php
//form validation for general entry form
// define variables and set to empty values
$clientErr = $matterErr = $dateErr = $timeErr = $noteErr= "";
$client = $matter = $date = $time = $note = "";
//on post, check to see if variable is empty. if not empty
//parse it and assign value back to variable name
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$complete = true;
$postArray = [];
if (empty($_POST["client"])) {
$clientErr = "*A client name is required. ";
$complete = false;
}else {
$client = test_input($_POST["client"]);
//$postArray[] = $client;
}
if (empty($_POST["matter"])) {
$matterErr = "*A matter name is required. ";
$complete = false;
}else {
$matter = test_input($_POST["matter"]); //remove $client and assign value to $matter
}
if (empty($_POST["date"])) {
$dateErr = "*A date is required. ";
$complete = false;
}else {
$date = test_input($_POST["date"]); //remove $client and assign value to $date
}
if (empty($_POST["time"])) {
$timeErr = "*A time entry is required. ";
$complete = false;
}else {
$time = test_input($_POST["time"]); //remove $client and assign value to $time
}
if (empty($_POST["note"])) {
$noteErr = "*A note is required. ";
$complete = false;
} else {
$note = test_input($_POST["note"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
<label for="client">Client:</label>
<input type="text" placeholder = "Enter Client Name" name="client"> *
<label for="matter">Matter:</label>
<input type="text" placeholder = "Enter Matter Name" name="matter"> *
<label for="date">Date:</label>
<input type="text" placeholder = "Enter Date" name="date"> *
<label for="time">Time:</label>
<input type="text" placeholder ="Time to nearest tenth hour" name="time"> *
<label for="note">Note:</label>
<textarea name="note" placeholder ="Enter Any Notes" rows="4" cols="40"></textarea>
<input type="submit" name="submit" value="Submit" class="submitbutton">
</form>
<div class="errorDiv">
<?php
echo $clientErr;
echo $matterErr;
echo $dateErr;
echo $timeErr;
echo $noteErr; // echo noteerror here.........
?>
</div>
<div class ="displayDiv">
<?php
echo "<h2>Your Input:</h2>";
echo $client;
echo "<br>";
echo $matter;
echo "<br>";
echo $date;
echo "<br>";
echo $time;
echo "<br>";
echo $note;
?>
</div>
</body>
</html>
Here you assign all values to single variable $client and echo all different variable so assign value to particular variable like $matter, $date, $time. And you forget to echo $noteerror in error messsages.

You copy and pasted your else block, didn't you? In each block you assign the value to $client and thereby overwrite it with each new $_POST value. Change the other assignments to $client to $time or appropriate and try that.
For example this
$client = test_input($_POST["date"]);
should probably be
$date = test_input($_POST["date"]);

Why are you assigning all the values to same $client variable? It has to be replaced with different variables.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$complete = true;
$postArray = [];
if (empty($_POST["client"])) {
$clientErr = "*A client name is required. ";
$complete = false;
}else {
$client = test_input($_POST["client"]);
//$postArray[] = $client;
}
if (empty($_POST["matter"])) {
$matterErr = "*A matter name is required. ";
$complete = false;
}else {
$matter= test_input($_POST["matter"]);
}
if (empty($_POST["date"])) {
$dateErr = "*A date is required. ";
$complete = false;
}else {
$date= test_input($_POST["date"]);
}
if (empty($_POST["time"])) {
$timeErr = "*A time entry is required. ";
$complete = false;
}else {
$time= test_input($_POST["time"]);
}
if (empty($_POST["note"])) {
$noteErr = "*A note is required. ";
$complete = false;
} else {
$note = test_input($_POST["note"]);
}

Related

Attempting to use if !isset to display results without the form

I am attempting to display the results without the form being shown at the same time. So, initially when they go to the URL they see the form, and after they fill out the form and the form validation and required fields and URL is valid. Here is what I started with.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = test_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurl = "";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
?>
</body>
</html>
Here is what I have tried.
I've tried adding else statements after body and before results. I'd like the results not to show until after form submitted.
Here's what I have so far...
I tried to add the below after the body
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['name']) == "")){
?>
Then I added:
<?php
} else {
//Retrieve show string from form submission.
Just after
// define variables and set to empty values
Finally added:
<?php
} ?>
Before /body
Here is what I tried.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['TXTlinkname'] && $_POST['TXTurl']) == "")){
?>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = HTML_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurl = "";
} else {
$TXTurl = HTML_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = HTML_input($_POST["TXTurl"]);
}
}
function HTML_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
} else {
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
?>
<button onclick="location = location.href">Go Back</button>
<?php
} ?>
</body>
</html>
So, initially when they go to the URL they see the form, and after they fill out the form and the form validation and required fields and URL is valid.
The big issue I see with your code is the if statement. The variables are not defined unless form hasn't been submitted. What I've changed is moved the function to be defined globally along with the variable names, and inverted the if statement. PHP Tags, you don't need them everywhere. One wrapper is good enough.
I'm not sure about what your result is, but for what you asked, I shall provide.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
function HTML_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$TXTlinkname = $TXTurl = "";
$TXTlinknameErr = $TXTurlErr = "";
//If form not submitted, display form.
if (isset($_POST['submit'])){
if (empty($_POST['TXTurl'])) {
$TXTurlErr = "URL is required";
} else {
$TXTurl = HTML_input($_POST['TXTurl']);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST['TXTname'])) {
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = HTML_input($_POST['TXTname']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$TXTlinknameErr = "Only letters and white space allowed";
}
}
}
if (empty($TXTurlErr) && empty($TXTlinknameErr) && isset($_POST['submit'])) {
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">' . $TXTlinkname . '</textarea>';
echo '<button onclick="location = location.href">Go Back</button>';
} else {
echo '<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'">
Name: <input type="text" name="TXTname" value="'.$TXTlinkname.'">
<span class="error">* '. $TXTlinknameErr .'</span>
<br><br>
URL: <input type="text" name="TXTurl" value="'.$TXTurl.'">
<span class="error">'.$TXTurlErr.'</span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>';
}
?>
</body>
</html>
Tested locally on XAMPP
You have to have a variable that tells you if you're going to show the textarea or not...
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$TXTlinknameErr = $TXTurlErr = "";
$TXTlinkname = $TXTurl = "";
$show_textarea = false; //DEFAULT
if (isset($_POST['submit'])) { //The form is sent...
$show_textarea = true; //Then this is DEFAULT!!
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["TXTlinkname"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTlinknameErr = "Name is required";
} else {
$TXTlinkname = test_input($_POST["TXTlinkname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$TXTlinkname)) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTlinknameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["TXTurl"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurl = "";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$TXTurl)) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurlErr = "Invalid URL";
}
}
if (empty($_POST["TXTurl"])) {
$show_textarea = false; //DON'T SHOW TEXTAREA
$TXTurlErr = "URL is required";
} else {
$TXTurl = test_input($_POST["TXTurl"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($show_textarea === false) {
?>
<h2>Create HTML Link</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="TXTlinkname" value="<?php echo $TXTlinkname;?>">
<span class="error">* <?php echo $TXTlinknameErr;?></span>
<br><br>
URL: <input type="text" name="TXTurl" value="<?php echo $TXTurl;?>">
<span class="error"><?php echo $TXTurlErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
if (isset($_POST['submit'])) { //The form is sent...
if ($show_textarea === true ) { //...AND the form has valid values
echo "<h2>Your HTML Code:</h2>";
echo "<br>";
echo '<textarea name="htmlcode" rows="10" cols="60">
' . $TXTlinkname . '
</textarea>';
}
}
?>
</body>
</html>
try this one:
if (!$_POST) || $_POST['TXTlinkname'] == "" && $_POST['TXTurl']) == "")){

Can I handle a form with php if else statement in action attribute of HTML form?

I am writing a form to create a login username and password.
If the account creation is successful, I would like the user to then be taken to the actual LOGIN form.
I have created a series of checks with the variable $errcheck being passed so the program knows what to do. If there is an error, $errcheck will be set to 1. Its default is 0.
If there are errors in the input fields, the account creation form will be displayed again and if everything is fine then it will INSERT user details into the table and take the user to the LOGIN page.
However, I can only get the page to reload itself each time after the info is added to the table. Is what I'm doing with the action part of the form even allowed? I went ahead and included all of my code in case there were any questions about it. Thank you.
<!DOCTYPE html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$busow_namef = $busow_namel= $owner_email = $bus_psswd = $psswd_confirm = "";
$busname_ERR = $busowname_ERR = $owneremail_ERR = $psswd_ERR =
$psswdconfirm_ERR = "";
$errcheck = 0;
if ($_SERVER["REQUEST_METHOD"]=="POST") {
//??????????????????? Check Login information ???????????????????
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($_POST["busow_namef"])) {
$busowname_ERR = "Business owner's name is required";
$errcheck = 1;
} else {
$busownamef = test_input($_POST["busow_namef"]);
}
if (empty($_POST["busow_namel"])) {
$busowname_ERR = "business owner's name is required";
$errcheck = 1;
} else {
$busownamel = test_input($_POST["busow_namel"]);
}
if (empty($_POST["bus_psswd"])) {
$psswd_ERR = "You must enter a password.";
$errcheck = 1;
} else if ((mb_strlen($_POST["bus_psswd"])) < 8) {
$psswd_ERR = "The password must be 8-10 characters long and only include numbers and letters.";
$errcheck = 1;
} else {
$bus_psswd = test_input($_POST["bus_psswd"]);
}
if (empty($_POST["psswd_confirm"])) {
$psswdconfirm_ERR = "Please confirm password.";
$errcheck= 1;
} else if ($_POST["psswd_confirm"] != $_POST["bus_psswd"]) {
$psswdconfirm_ERR = "The passwords do not match.";
$errcheck = 1;
} else {
$psswd = test_input($_POST["psswd_confirm"]);
$h_psswd = password_hash($psswd, PASSWORD_DEFAULT);
}
if (empty($_POST["tandc"])) {
$checktandc_ERR= "You must accept the terms and conditions.";
$errcheck= 1;
} else {
$tandc = test_input($_POST["tandc"]);
}
if (empty($_POST["owner_email"])) {
$owneremail_ERR = "Please enter an email address.";
$errcheck = 1;
} else {
$_POST["owner_email"] = (filter_var($_POST["owner_email"], FILTER_SANITIZE_EMAIL));
}
if (filter_var($_POST["owner_email"] , FILTER_VALIDATE_EMAIL)){
$owneremail = $_POST["owner_email"];
} else {
$owneremail_ERR = "Please enter a valid email address.";
$errcheck = 1;
}
//???????????????? Connect to database ??????????????????????????
$link = mysqli_connect('domain', 'user', 'passwd');
if (!$link) {
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db(database, $link);
if (!mysqli_select_db(louisville_ky1, $link)) {
echo "database not selected";
} else {
$sql = "SELECT owner_email FROM 3bus_owners WHERE owner_email = '$owneremail' ";
$result = mysql_query($sql, $link);
if (mysql_num_rows($result) > 0 ) {
$errcheck = 1;
$owneremail_ERR = "This email is already registered. Please register with another address or click login.";
} else {
$errcheck = 0;
$query = "INSERT INTO 3bus_owners (owner_email, h_psswd, busow_namef, busow_namel) VALUES ('$owneremail', '$h_psswd', '$busownamef',
'$busownamel')";
$result2 = mysql_query($query, $link);
} //end if num rows >0
}//end connection check
} // ???????????????????? end if server request method ????????????????
?>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~Begin HTML FORM~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<h2>Create Business Login</h2>
<br>
<form method="post" action="<?php if ($errcheck = 1) { echo
htmlspecialchars($_SERVER["PHP_SELF"]);
} else { echo 'ownersignin.php'; }?>">
Business Owner's Name:<br>
First Name:<br><input type="text" name="busow_namef" value="<?php echo
$busow_namef;?>">
<span class="error">* <?php echo $busowname_ERR;?></span>
<br>
Last Name:<br><input type="text" name="busow_namel"value="<?php echo
$busow_namel;?>">
<span class="error">* <?php echo $busowname_ERR;?></span>
<br>
Business Owner's E-mail: *this will be your username for login and does not have to be posted in listing
<br>
<input type="text" name="owner_email" size="40"value="<?php echo
$owner_email;?>">
<span class="error">*<?php echo $owneremail_ERR;?></span>
<br><br>
Password: <input type="password" name="bus_psswd" size="11" maxlength="10">
<span class="error">*<?php echo $psswd_ERR;?></span>
<br>
Confirm Password: <input type="password" name="psswd_confirm" size="11" maxlength="10">
<span class="error">*<?php echo $psswdconfirm_ERR;?></span>
<br>
<br>
<input type="checkbox" name="tandc">I have read and accept the
<a href="/termsandconditions.php" target= "_blank">Terms and
Conditions</a>.
<span class="error">*<?php echo $checktandc_ERR;?></span>
<br>
<br>
<input type="submit" name="submit" value="Create Login">
</form>
</body>
snippit from above:
<form method="post" action="<?php if ($errcheck = 1) { echo htmlspecialchars($_SERVER["PHP_SELF"]); } else { echo 'ownersignin.php'; }?>">
I have never seen a form action attribute written like this, but... try changing the "double quotes" around "PHP_SELF" to single quotes: $_SERVER['PHP_SELF']. That could be causing a problem because it might be getting interpreted as:
action="<?php if ($errcheck = 1) { echo htmlspecialchars($_SERVER["
Then, verify that this code sample didn't come from the page: "ownersignin.php". It just sounds like that would be the name of this page instead of the name of the page the form would redirect to.
echo 'ownersignin.php';
If this is the name of the page your code is in, it would send you in an infinite loop.
You shouldn't reprint the registration form when the registration is successful. Instead, redirect the user to the signin form.
After all the validation checks, do:
if (!$errcheck) {
header("Location: ownersignup.php");
exit;
}
?>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~Begin HTML FORM~~~~~~~~~~~~~~~~~~~~~~~~~ -->
<h2>Create Business Login</h2>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
...

Am I missing something ? PHP MYSQL connection through Xammp

I'm trying to add form data into my database table on Xampp ,but while My echo displays everything properly ,it doesn't input anything into the database table and I wonder if I'm missing something here.I made sure to spell everything the same ,so I doubt it's a spelling error atleast....Any help,suggestions and or corrections are greatly appreciated !
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
// define variables and set to empty values
$VarErr = $PavErr = $AdErr = $PkErr = $KiekErr = "";
$Vardas = $Pavarde = $Adresas = $Pk = $Kiekis = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Vardas"])) {
$VarErr = "Įveskite vardą";
} else {
$Vardas= test_input($_POST["Vardas"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Vardas)) {
$VarErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Pavarde"])) {
$PavErr = "Įveskite pavardę";
} else {
$Pavarde = test_input($_POST["Pavarde"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$Pavarde)) {
$PavErr = "Galima vesti tik su raidėmis";
}
}
if (empty($_POST["Adresas"])) {
$AdErr = "Įveskite adresą";
} else {
$Adresas= test_input($_POST["Adresas"]);
}
if (empty($_POST["Pk"])) {
$Pk = "Įveskite prekės kodą";
} else {
$Pk = test_input($_POST["Pk"]);
}
if (empty($_POST["Kiekis"])) {
$KiekErr = "Įveskite kiekį";
} else {
$Kiekis = test_input($_POST["Kiekis"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Vardas: <input type="text" name="Vardas" value="<?php echo $Vardas;?>">
<span class="error">* <?php echo $VarErr;?></span>
<br><br>
Pavarde: <input type="text" name="Pavarde" value="<?php echo $Pavarde;?>">
<span class="error">* <?php echo $PavErr;?></span>
<br><br>
Adresas: <input type="text" name="Adresas" value="<?php echo $Adresas;?>">
<span class="error"><?php echo $AdErr;?></span>
<br><br>
Pk: <input type="number" name="Pk" value="<?php echo $Pk;?>">
<span class="error"><?php echo $PkErr;?></span>
<br><br>
Kiekis:<input type="number" name="Kiekis" value="<?php echo $Kiekis;?>">
<span class="error"><?php echo $KiekErr;?></span>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $Vardas;
echo "<br>";
echo $Pavarde;
echo "<br>";
echo $Adresas;
echo "<br>";
echo $Pk;
echo "<br>";
echo $Kiekis;
$host = "localhost";
$user = "root";
$password ="";
$database = "uzsakymas";
try{
$connect = mysqli_connect($host,$user,$password,$database);
}
catch(mysqli_sql_exception $ex){
echo 'database connection error';
}
if(isset($_POST['insert'])) {
$Vardas = $_POST['Vardas'];
$Pavarde = $_POST['Pavarde'];
$Adresas = $_POST['Adresas'];
$Pk = $_POST['Pk'];
$Kiekis = $_POST['Kiekis'];
$insert_query = "INSERT INTO uzsakymai (Vardas,Pavarde,Adresas,Pk,Kiekis)VALUES('$Vardas','$Pavarde','$Adresas','$Pk','$Kiekis')";
try {
$insert_result = mysqli_query($connect,$insert_query);
if($insert_result){
if(mysqli_affected_rows($connect) > 0)
{
echo 'Data Inserted';
}else{
echo'Data not Inserted';
}
}
} catch(Exception $ex) {
echo 'Error Insert'.$ex->getMessmessage();
}
}
?>
</body>
</html>
hi your are checking value in insert isset($_POST['insert']) but insert name not assign in any control so assign insert name to your submit control check below :
<input type="submit" value="Submit" name="insert">
I'm kinda confused with your code but I think the wrong part is in here:
<input type="submit" name="submit" value="Submit">
You have this submit but look at this:
if(isset($_POST['insert']))
You are trying to check if POST is set to insert instead of submit.

PHP Form executing POST request on load

I am creating an update form, but when I click on the update button it redirects to my update page, and triggers the POST request which makes it a valid post and does not ask for any information to update.
<!DOCTYPE html>
<html>
<?php require ('template/functions.php');
$ID = $_GET['id'];
$sql_query = "SELECT * FROM specialties WHERE id='".$ID."'";
$results = mysqli_query($connect,$sql_query);
$spc = mysqli_fetch_assoc($results);
$error = "";
$specialist_section = false;
$description_section = false;
$specilist_exist = false;
$valid_post = true;
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "post") {
valid();
if ($valid_post){
$sql_query = "UPDATE specialties SET ";
$sql_query .= "specialty='".$_POST['specialty']."',";
$sql_query .= "description='".$_POST[description]."'";
$sql_query .= " WHERE id='".$_GET['id']."'";
$result = mysqli_query($connect,$sql_query);
if (!results){
print "MYSQL_ERROR: ".mysqli_error($connect);
$valid_post = false;
$specilist_exist = true;
$error .= "Specialty already exist <br/>";
}
}else{
$valid_post = false;
}
}
?>
<head>
<title>Specialist Lookup </title>
</head>
<body>
<div class="container">
<?php
if ($valid_post){?>
<h2>Update Complete</h2>
<?php
}else{
if ($error) { ?>
<h3 style="color:red;"><?php echo $error ?> </h3> <?php }?>
<h1>Update Specialist</h1>
<form action="update.php" method="post">
<div class="form-group">
<label for="specialty" style="color:<?php if ($specialist_section){echo "red";}else{ echo "black";} ?>">Specialty:</label>
<input type="text" class="form-control" id="sp" name="specialty" value="<?php echo $spc['specialty'] ;?>" >
</div>
<div class="form-group">
<label for="description" style="color:<?php if ($description_section){echo "red";}else{ echo "black";} ?>">Description:</label>
<textarea class="form-control" rows="5" id="comment" name="description"><?php echo $spc['description'] ; ?></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<?php
}
?>
<div>
</body>
<?php
require ('template/footer.php');
?>
/*Reference for the function*/
function valid(){
$valid_post = true;
if (empty($specialty)) {
$valid_post = false;
$specialist_section = true;
$error = "Please fill in the Specialist section";
}
elseif (empty($description)) {
$valid_post = false;
$error = "Please fill in the description section";
$description_section = true;
}
elseif (empty($description) and empty($specialty)) {
$valid_post = false;
$error = "Please fill in the specialty and description section";
$description_section = true;
}
else{
$valid_post = true;
}
}
By default you set
$valid_post = true;
You need to change the logic:
<!DOCTYPE html>
<html>
<?php require ('template/functions.php');
...
$valid_post = false;
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "post") {
$valid_post = valid();
if ($valid_post){
// ...
}
}
?>
<head>
<title>Specialist Lookup </title>
</head>
<body>
<div class="container">
<?php
if ($valid_post){?>
<h2>Update Complete</h2>
<?php
}else{
// ...
}
?>
<div>
</body>
I do not know what happens in valid() function. But I suggest you this pattern:
$validPost = false;
if (valid()) {
$validPost = true;
}
or
$validPost = valid();
Not too sure how you write your valid() function.
By looking at the code, $valid_post is set to be true by default, so you might want to have a look at your valid() function to see if it is actually setting $valid_post to be false if it is not valid, otherwise it will always trigger your update function even if there is no valid form data.
if your valid() function is returning boolean then just modify your code
change
valid()
to
$valid_post = valid()
Also, you probably dont need else in your code at all, $valid_post = valid() this will simply assign a boolean value already, therefore the else part will be redundant.
Let me know if you have any question

php - preg_match issue with empty form fields on update query

The following flags an error if a form field is empty and also flags an error if anything other than letters are entered in the form input.
if (empty($_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter feed title";
} elseif (preg_match('/[^a-zA-Z]/i',$_POST["feedtitle"])) {
$has_errors = false;
$feedtitleErr = "Enter text only";
} else {
$feedtitle = validate_input($_POST["feedtitle"]);
}
When created the form this works fine. When editing the form data however is the input is left empty the empty field error "Enter feed title" does not fire and if I enter anything other than letters e.g. numbers no value is passed i.e. the variable $feedtitle is blank. If I enter text however it saves.
I don't think the query is the issue.
$Query = "UPDATE ccregisterfeed SET author='$author', category='$category',
copyright='$copyright', feeddescription='$feeddescription', feedtitle='$feedtitle',
websitelink='$websitelink', imagelink='$imagelink', imagetitle='$imagetitle',
subtitle='$subtitle' WHERE id='$feedid' AND username ='$user'";
FULL SCRIPT
<?php
include "connect.php";
require "authenticate.php";
error_reporting(E_ERROR);
$message = $_GET['message'];
$user = $_SESSION['UserName'];
//declare form field and form field error variables
$authorErr = $categoryErr = $copyrightErr = $feeddescriptionErr = $feedlinkErr = $feedtitleErr = $websitelinkErr = $imagelinkErr = $imagetitleErr = $subtitleErr = "";
$author = $category = $copyright = $feeddescription = $feedlink = $feedtitle = $websitelink = $imagelink = $imagetitle = $subtitle = "";
//form field validation
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['Submit']))
{
$has_errors = false;
if (empty($_POST["author"])) {
$has_errors = true;
$authorErr = "Enter your name";
}else{
$author = validate_input($_POST["author"]);
}
if (empty($_POST["category"])) {
$has_errors = true;
$categoryErr = "Enter a category";
}else {
$category = validate_input($_POST["category"]);
}
if (empty($_POST["copyright"])) {
$has_errors = true;
$copyrightErr = "Enter copyright details";
} else {
$copyright = validate_input($_POST["copyright"]);
}
if (empty($_POST["feeddescription"])) {
$has_errors = true;
$feeddescriptionErr = "Enter feed description";
} else {
$feeddescription = validate_input($_POST["feeddescription"]);
}
if (empty($_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter feed title";
} elseif (preg_match('/[^a-zA-Z]/i',$_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter text only";
} else {
$feedtitle = validate_input($_POST["feedtitle"]);
}
if (empty($_POST["websitelink"])) {
$has_errors = true;
$websitelinkErr = "Enter link to website";
} else {
$websitelink = validate_input($_POST["websitelink"]);
}
if (empty($_POST["imagelink"])) {
$has_errors = true;
$imagelinkErr = "Enter link to image";
} else {
$imagelink = validate_input($_POST["imagelink"]);
}
if (empty($_POST["imagetitle"])) {
$has_errors = true;
$imagetitleErr = "Enter image name";
} else {
$imagetitle = validate_input($_POST["imagetitle"]);
}
if (empty($_POST["subtitle"])) {
$has_errors = true;
$subtitleErr = "Enter feed subtitle";
} else {
$subtitle = validate_input($_POST["subtitle"]);
}
// var_dump ($date);
// var_dump ($feedlink);
// var_dump ($feeddescription);
//write edited data into tables matching logged in user with their data
$feedid = mysql_real_escape_string($_POST['feedid']);
$date = date("Y-m-d H:i:s");
$feeddescription = str_replace("_", "", $feeddescription);
$feeddescription = str_replace("-", "", $feeddescription);
$feeddescription = str_replace("!", "", $feeddescription);
$feeddescription = str_replace("#", "", $feeddescription);
$feeddescription = str_replace("'", "", $feeddescription);
$Query = "UPDATE ccregisterfeed SET author='$author', category='$category', copyright='$copyright', feeddescription='$feeddescription', feedtitle='$feedtitle', websitelink='$websitelink', imagelink='$imagelink', imagetitle='$imagetitle', subtitle='$subtitle' WHERE id='$feedid' AND username ='$user'";
if($sql = mysql_query($Query)) {
header("location: rss.php");
// header("location: feededit.php");
} else {
die("Query was: $Query. Error: ".mysql_error());
}
}
//show logged in user their updated data
$user = $_SESSION['UserName'];
$result = mysql_query("SELECT * FROM ccregisterfeed WHERE username = '$user'") or die(mysql_error());
while($row = mysql_fetch_array($result)){
$id=$row['id'];
$author = $row['author'];
$category = $row['category'];
$copyright = $row['copyright'];
$feeddescription = $row['feeddescription'];
$feedtitle = $row['feedtitle'];
$websitelink = $row['websitelink'];
$imagelink = $row['imagelink'];
$imagetitle = $row['imagetitle'];
$subtitle = $row['subtitle'];
}
//delete form and image data when users clicks delete button
if (isset($_POST['Delete'])){
$deleteuser = $_POST['Delete'];
mysql_query("DELETE FROM ccregisterfeed WHERE id = '$deleteuser'");
mysql_query("ALTER TABLE ccregisterfeed AUTO_INCREMENT = 1");
$message = 'Feed Deleted';
header("Location: feededit.php?&message=".urlencode($message));
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<form action="feededit.php" method="post" enctype="multipart/form-data" name="edit" id="editfeed">
<fieldset>
<div class="legendcreate">Feed Edit</div>
<div class="feedcontainer">
<div class="feedcontainerinner">
<div><label class="labelshow">Author</label><input id="author" class="insetfeed" name="author" type="text" placeholder="Author" value="<?PHP print $author ; ?>"/><p class="errorinput"><?php echo $authorErr;?></p></div>
<?php if(isset($_GET['message']) && !empty($message)): ?>
<div class="messagebox">
<?php echo $message ?>
</div>
<?php endif; ?>
<div><label class="labelshow">Category</label><input id="category" class="insetfeed" name="category" type="text" placeholder="Category" value="<?PHP print $category; ?>"/><p class="errorinput"><?php echo $categoryErr;?></p></div>
<div><label class="labelshow">Copyright</label><input id="copyright" class="insetfeed" name="copyright" type="text" placeholder="Copyright" value="<?PHP print $copyright; ?>"/><p class="errorinput"><?php echo $copyrightErr;?></p></div>
<div><label class="labelshow">Feed Title</label><input id="feedtitle" class="insetfeed" name="feedtitle" type="text" placeholder="Feed Title" value="<?PHP print $feedtitle; ?>"/><p class="errorinput"><?php echo $feedtitleErr;?></p></div>
<div><label class="labelshow">Website Link</label><input id="websitelink" class="insetfeed" name="websitelink" type="text" placeholder="Website Link" value="<?PHP print $websitelink; ?>"/><p class="errorinput"><?php echo $websitelinkErr;?></p></div>
<div><label class="labelshow">Image Link</label><input id="imagelink" class="insetfeed" name="imagelink" type="text" placeholder="Image Link" value="<?PHP print $imagelink; ?>"/><p class="errorinput"><?php echo $imagelinkErr;?></p></div>
<div><label class="labelshow">Image Title</label><input id="imagetitle" class="insetfeed" name="imagetitle" type="text" placeholder="Image Title" value="<?PHP print $imagetitle; ?>"/><p class="errorinput"><?php echo $imagetitleErr;?></p></div>
<div><label class="labelshow">Subtitle</label><input id="subtitle" class="insetfeed" name="subtitle" type="text" placeholder="Subtitle" value="<?PHP print $subtitle; ?>"/><p class="errorinput"><?php echo $subtitleErr;?></p></div>
<div><textarea id="description" name="feeddescription" class="textareadescription" placeholder="Enter feed description"><?php
$out = htmlspecialchars_decode($feeddescription);
$out = str_replace( '\n', '<br />', $out );
echo $out;
?></textarea>
<div class="submit"><input name="Submit" type="submit" class="submitbtn" value="Save"/></div>
<div class="delete"><input name="deletebtn" type="submit" class="resetbtn" value="Delete"/></div>
<input type="hidden" name="feedid" value="<?phpecho $id;?>"/>
</div>
</div>
</div>
</form>
</fieldset>

Categories