how to fix error of empty $_POST['name'] - php

I want to have a form with php. but for many hours I'm involved an error and the error is when $_POST=['name'] wants to be checked empty or not it is empty.
When I check the database the row is white and nothing is there.
for checking if the $_POST is empty or not I print word 'empty' to be determined it's empty and it will be printed 'empty';
where is my mistake is it related to database mysql or not just in code?
please help me I got confused and bored.
this is whole of my codes:
<!doctype html>
<html lang="fa">
<head>
<meta charset="utf-8">
<title>form</title>
<link href="addContact.css" rel="stylesheet"/>
<link href="main.css" rel="stylesheet"/>
<link href="table.css" rel="stylesheet"/>
</head>
<body>
<?php
$name = "";
$nameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
echo 'empty';
$nameErr = "Name is required";
} else {
echo 'full';
$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";
}
}
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO abc (firstname)
VALUES ('$name')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
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"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
thank you in advance

The problem is in use of empty()
You can use it on variables not on values.
See here for PHP documentation page.
To check this, first save it in another variable and then check:
$tempVal = $_POST["name"];
if (empty($tempVal))

you can use this simple example
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>You can use the following form again to enter a new name.";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
i suggest this:
Understanding $_SERVER['PHP_SELF']

Related

data cannot pass to another page after submitted

I wanted to pass the form data to another page after validate.
The user have to enter the correct data in order to proceed to next page.
I was trying to get the data from the first page but seems like it doesn't work.
<!DOCTYPE html>
<html>
<head>
<meta charset ="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>
Register
</title>
</head>
<body>
<?php
// define variables and set to empty values
$firstNameErr = $surNameErr ="";
$firstName = $surName = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$valid = true;
if (empty($_POST["firstName"])) {
$firstNameErr = "FirstName is required";
$valid = false;
} else {
$firstName = test_input($_POST["firstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$firstNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["surName"])) {
$surNameErr = "surName is required";
$valid = false;
} else {
$surName = test_input($_POST["surName"]);
// check if name only contain letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$firstName)) {
$firstNameErr = "Only letters and white space allowed";
}
}
if($valid){
header('Location: successReg.php');
exit();
}
}
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"]);?>">
FirstName <input type="text" name="firstName" value="<?php echo $firstName;?>">
<span class="error">* <?php echo $firstNameErr;?></span>
<br><br>
SurName <input type="text" name="surName" value="<?php echo $surName;?>">
<span class="error">*<?php echo $surNameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
The code above shows the registration form.
After the "submit" button is pressed, it send to successReg.php
Here is the successReg.php code:
<!DOCTYPE html>
<html lang= "en">
<head>
<meta charset = "UTF-8" />
<title> Register successfully</title>
</head>
<body>
<?php
/* Get each parameter value from the request stream and using ternary if operators check each parameter to see if it was set. If it is, store it in a variable. */
$firstName = filter_has_var(INPUT_POST, 'firstName');
$surName = filter_has_var(INPUT_POST, 'surName' );
$firstName = filter_var($firstName , FILTER_SANITIZE_STRING , FILTER_FLAG_NO_ENCODE_QUOTES );
$firstName = filter_var($firstName,FILTER_SANITIZE_SPECIAL_CHARS);
$surName = filter_var($surName , FILTER_SANITIZE_STRING , FILTER_FLAG_NO_ENCODE_QUOTES );
$surName = filter_var($surName,FILTER_SANITIZE_SPECIAL_CHARS);
echo" $firstName";
?>
</body>
</html>
In the last line of the successReg.php page, I'm trying get the data from the submitted page to see whether the data can be retrieved or not.
And also, the successReg.php page is supposed to insert all the data into the database.
The echo $firstName is for testing purpose, but seems it doesn't work.
If the data is successfully passed from the form page, I will only continue with the sql code.
Is there any mistake, or what am I missing?
You are sending the user to the success page without it knowing which values to show. You could do this a few ways.
When you send them to the new page, you could amend the latest database insert id and then pick up the result on the success page (not than you have that active yet), or
You could just pass the values directly as a GET and display them on the success page.
Such as:
if($valid){
echo 'Continue on';
exit();
}

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

PHP - Web Form submit button not working

I am creating a form to connect to a database using PHP. I have the form semi-functional but when I'm trying to test it by pressing the submit button, it says file not found on the webpage.
Here is code for default.php:
<!DOCTYPE HTML> <html> <head>
<title>PHP FORM - 08246 ACW PART 2</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> <style> .error {color:
#FF0000;} </style> </head> <body>
<ul class="w3-navbar w3-black w3"> <li>Home</li> <li>Change location to staff member</li> <li>Current location of all staff</li> <li>Edit personal details of staff member</li> <li>List all locations and show list of people in selected location</li> <li>Staff member and list locations for last24 hours</li> </ul>
<div class="w3-container"> <h2> Web Form </h2> </div>
<div class="w3-container"> <?php // defining the variables and setting them to empty values $first_nameErr = $SurnameErr = $usernameErr = $passwordErr = $previous_LocationErr = $current_LocationErr = $dateErr = $timeErr = $dErr = $tErr = ""; $first_name = $Surname = $username = $password = $previous_Location = $current_Location = $date = $time = $dErr = $tErr = "";
//----validation----
//first name if($_SERVER["REQUEST_METHOD"] == "POST"){ if(empty($_POST["first_name"])){ $first_nameErr = "First Name is required"; }else{ $first_name = test_input($_POST["first_name"]); //validation checking if(!preg_match("/^[a-zA-Z ]*$/",$first_name)){ $first_nameErr = "Please enter only letter and white space"; } }
//surname if($_SERVER["REQUEST_METHOD"]=="POST"){ if(empty($_POST["Surname"])){ $SurnameErr="Surname is required"; }else{ $Surname=test_input($_POST["Surname"]); //validation checking if(preg_match("/^[a-zA-Z ]*$/",$Surname)){ $SurnameErr = " Please enter only letters and white spaces"; } }
//date and time date_default_timezone_set('UTC');
$d = str_replace('/',',', '03/05/2016'); $t = str_replace(':',',', '13:38'); $date = $t.',0,'.$d; $fulldate = explode(',',$date); echo '<br>'; $h = $fulldate[0]; $i = $fulldate[1]; $s = $fulldate[2]; $m = $fulldate[3]; $d = $fulldate[4]; $y = $fulldate[5];
echo date("h-i-s-M-d-Y",mktime($h,$i,$s,$m,$d,$y))."<br>"; echo strtotime ("03/05/2016 13:38");
function test_input($data){ $data=trim($data); $data=stripslashes($data); $data=hmtlspecialchars($data); return $data; } ?>
<?php//database
#server info
#$servername = "SQL2008.net.dcs.hull.ac.uk";
#$username = "ADIR\463142";//userid
#$dbname = "rde_463132"; $servername = "SQL2008.net.dcs.hull.ac.uk"; $username = "username"; $myDB = "examples"; $myLocation = "location";
// Create connection $conn = new mysqli($servername, $username, $myLocation); // Check connection if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
// Create database $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) {
echo "Database created successfully"; } else {
echo "Error creating database: " . $conn->error; }
$conn->close(); ?>
<p><span class="error">* are required field.</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> First Name: <input type="text" name="first_name"><br> <span class="error">* <?php echo $First_nameErr;?></span> <br> Surname: <input type="text" name="Surname"><br> <span class="error">* <?php echo $SurnameErr;?></span> <br> Username: <input type="text" name="username"><br> <span class="error">* <?php echo $username;?></span> <br> Current Location: <input type="text" name="current_Location"><br> <span class="error">* <?php echo $current_Location;?></span> <br> Date: <input type="text" name="date"><br> <span class="error">* <?php echo $date;?></span> <br> Time: <input type="text" name="time"><br> <span class="error">* <?php echo $time;?></span> <br>
<input type="submit" name="submit" value="Submit"> </form>
</div> </body> </html>
I am new to this language and still learning.
Any help or advice would be greatly appreciated.
Thank you
What version of PHP you are using to run this script?
As I can see you are using "Register globals" setting to get $_POST data: http://php.net/manual/en/security.globals.php
If you have PHP version 5.4+ you should use $_POST['form_field_name1'] ... $_POST['form_field_nameN'] to get form data.
Add check:
if (!empty($_POST)) { /* Form validation data goes here */ }
File is incorrect, the form action url points to default.php but your filename is defaul.php
Make if default.php instead of defaul.php
For better handling:
In console of your browser, please check the http call, you can see the error it is showing if its a 500 (check logs / enable the debug mode)

Display none result as default value with php

I am building a small web interface for MySQL database using PHP. One task is to allow users to be able to input a string into a text field and the system should return the name of any table that contains this string in its name. However, my problem is that, every time you enter in the web interface, it will by default display all the table names. Here is my complete code.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<style>
.error {color: #FF0000;}
</style>
<body>
<h1>This is H1</h1>
<?php
$servername = "xxx";
$username = "xxx";
$password = xxx;
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$search = $searchErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["search"])) {
$searchErr = "Search keyword is required";
} else {
$search = test_input($_POST["search"]);
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;
}
?>
<h2>Search Keyword</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Search: <input type="text" name="search" value="<?php echo $search;?>">
<span class="error">* <?php echo $searchErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit"> </form>
<?php
echo '<h2> Search Result: </h2>';
$searchSQL = "SELECT table_name FROM information_schema.tables
WHERE LOWER(table_name) LIKE LOWER('%$search%')
AND table_schema = 'xxx'";
$result = $conn->query($searchSQL);
echo '<form method="POST" action="show_columns.php">'; // opening form tag
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$table_name = $row['table_name'];
echo "<input type='submit' name='table_name' value='$table_name' /> <br/>";
}
} else {
echo ' ';
}
echo '</form>'; // closing form tag
?>
</body>
</html>
For example, every time I enter the web end, the search result will display all the table names. I assume that it might take empty string as the search key word? Any ideas on how to get around with it? Thanks in advance!
This might not be the cleanest solution, but I add a condition before executing the search queries
if ($search!='')
{$result = $conn->query($searchSQL);}
else {...}
...
and the problem is solved. Thanks for all your suggestions.

Php form value not matching [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I have reviewed the code and everything appears right so I am not sure what is wrong. I keep getting the following error s1s01 1136 column count does match.
I believe I used all the correct security codes please note if I did not thank you.
<?php
include ('wording/en-translation.php');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<?php
// define variables and set to empty values
$user_nameErr = $user_emailErr = "";
$user_name = $user_email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_name"])) {
$user_nameErr = "Name is required";
} else {
$user_name = mysql_real_escape_string($_POST["user_name"]);
//check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/",$user_name)) {
$user_nameErr="Only letters and white spaces allowed";
}
}
if (empty($_POST["user_email"])) {
$user_emailErr = "Email is required";
} else {
$user_email = mysql_real_escape_string($_POST["user_email"]);
//check if email is well-formed
if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
$user_emailErr = "Invalid Email Format";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user_name = mysql_real_escape_string($_POST["user_name"]);
$user_email = mysql_real_escape_string($_POST["user_email"]);
}
function mysql_real_escape_string($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="user_name"><?php echo WORDING_REGISTRATION_USERNAME; ?></label>
<input id="user_name" type="text" pattern="[a-zA-Z0-9]{2,64}" value="<?php echo $user_name; ?>" name="user_name" required />
<span class="error">* <?php echo $user_nameErr;?></span><br>
<label for="user_email"><?php echo WORDING_REGISTRATION_EMAIL; ?></label>
<input id="user_email" type="email" name="user_email" value="<?php echo $user_email; ?>" required />
<span class="error">* <?php echo $user_emailErr;?></span>
<input type="submit" name="register" value="<?php echo WORDING_REGISTER; ?>" />
</form>
<?php
echo $user_name;
echo "<br>";
echo $user_email;
echo "<br>";
?>
<?php
$servername = "localhost";
$username = "admin";
$password = "";
$dbname = "login";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(user_name, user_email)
VALUES(
". mysql_real_escape_string($user_name) ."',
". mysql_real_escape_string($user_email) ."'
)";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
</
You're generating broken SQL, by having completely WRONG quoting on your values:
$sql = "INSERT INTO users(user_name, user_email)
VALUES(
". mysql_real_escape_string($user_name) ."',
^---start sql string
". mysql_real_escape_string($user_email) ."'
^---end of sql string
)";
That means you're generating
INSERT INTO users (user_name, user_email) VALUES (Bob, 'bob#example.com')
^--unknown field
you're also mixing mysql libraries, which is flat out IMPOSSIBLE, and you're vulnerable to sql injection attacks.
In short, this code is totally cargo-cult programming, and you really need to sit back and learn PHP properly.

Categories