How to fix variable declaration in PHP from a form submit - php

I am creating a registration page. Here is my PHP code:
<?php
$id = $name = $pwd = $confirm_pwd = $eamil = $phone = $dob = $region = $city = "";
$idErr = $nameErr = $passErr = $phoneErr = $emailErr = $message = $dobErr = $regionErr = $cityErr = "";
if(isset($_POST['submit'])) {
if (empty($_POST["national_id"])) {
$nameErr = "national id is required";
} else {
$id = test_input($_POST["national_id"]);
}
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["pwd"])) {
$passErr = "password is required";
} else {
$pwd = test_input($_POST["pass"]);
}
/* Password Matching Validation */
if($_POST['pwd'] != $_POST['confirm_pwd']){
$message = 'Passwords should be same<br>';
}
else {
$pwd = test_input($_POST["pwd"]);
}
if (empty($_POST["email"])) {
$emailErr = "email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["phone"])) {
$phoneErr = "phone is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["date_of_birth"])) {
$dobErr = "date of birth is required";
} else {
$dob = test_input($_POST["date_of_birth"]);
}
if (empty($_POST["region"])) {
$regionErr = "region is required";
} else {
$region = test_input($_POST["region"]);
}
if (empty($_POST["city"])) {
$cityErr = "city is required";
} else {
$phone = test_input($_POST["city"]);
}
}
else{
$con = new mysqli("localhost","root","","seis") or die(mysql_error());
$id = $_POST["national_id"];
$name = $_POST["name" ];
$pwd = md5($_POST["pwd" ]);
$email = $_POST["email" ];
$phone = $_POST["phone" ];
$dob = $_POST["date_of_birth" ];
$region = $_POST["region" ];
$city = $_POST["city" ];
$national_id = trim($id);
$cust_name = trim($name);
$cust_pwd = trim($pwd);
$cust_email = trim($email);
$cust_phone = trim($phone);
$cust_dob = trim($dob);
$cust_region = trim($region);
$cust_city = trim($city);
$processvalue = "Insert INTO Registration
VALUES ('$national_id' ,'$cust_name', '$cust_dob' ,'$cust_email' , '$cust_pwd' , '$phone' , (select region_serial,city_serial from cities where region = '$cust_region' AND city = '$cust_city') )";
if (mysqli_query($con, $processvalue)) {
echo 'You are registered ';
} else {
echo "error:" .mysqli_error($con);
}
}
mysqli_close($con)
?>
I am trying to insert each variable to an SQL statement, but it seems like I have a problem with variable initialization.
This is the error I get:
Notice: Undefined index: national_id in
C:\xampp\htdocs\seis-new\signup.php on line 68
Notice: Undefined index: name in C:\xampp\htdocs\seis-new\signup.php
on line 69
Notice: Undefined index: pwd in C:\xampp\htdocs\seis-new\signup.php on
line 70
Notice: Undefined index: email in C:\xampp\htdocs\seis-new\signup.php
on line 71
Notice: Undefined index: phone in C:\xampp\htdocs\seis-new\signup.php
on line 72
Notice: Undefined index: date_of_birth in
C:\xampp\htdocs\seis-new\signup.php on line 73
Notice: Undefined index: region in C:\xampp\htdocs\seis-new\signup.php
on line 74
Notice: Undefined index: city in C:\xampp\htdocs\seis-new\signup.php
on line 75 error:Table 'seis.registration' doesn't exist

you have to use isset() function to check variable index is set or not

function empty() check value. If you will give assoc array, then you need to have given key.
Check first, if value exist in given key by isset().
Simply check, if this request is not good practice.
Your IF statement should look like:
$errors = [];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!isset($_POST["national_id"]) || empty($_POST["national_id"])) {
// didn't provide field national_id or is empty
$errors[] = "national id is required";
} else {
$id = test_input($_POST["national_id"]);
}
}
if (count($errors)) {
// You have errors
}

First of all what have you done on 2nd and 3rd line too many variables equal? Can you please tell whats you intention doing so...
The reason you are getting undefined indexes because you have problem in your form. Check all the name attributes in your form and use that names as indexes in your $_POST['index'] method....

On your first line, you mispelled the variable you wrote $eamil and every other line is written $email fix this and check if it works, it probably will.
I recommend you to write your IF statements to check for empty fields like this:
if (!empty($_POST["national_id"])) {
$id = test_input($_POST["national_id"]);
} else {
$nameErr = "national id is required";
}
Also, your $convariable is connecting to the database using mysqli but then you wrote mysql_error. You must use mysqliall the time, otherwise it don't detect the table you wish. And I would take the comments advices to improve the entire code, it's a bit messy and there's a lot of stuff than can retrieve errors.
Obs: Reputation lower than 50, cannot comment yet.

Related

How to access variable value from another php script

I have read so many pages and am stuck on this for the past three hours now because it just won't work.
I keep getting Notice: Undefined index: firstname
here is the bulk of the segment that isn't working:
$errMsg = "";
function sanitise($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST["firstname"]))
{
$firstname = $_POST["firstname"];
$firstname = sanitise($firstname);
if (!preg_match("/^[A-Za-z \-]+$/",$firstname))
{
$errMsg .= "First name must contain only letters or hyphens.<br/>";
}
if (strlen($firstname) > 40)
{
$errMsg .= "First name cannot be over 40 characters long.<br/>";
}
} else {
$errMsg .= "First name cannot be empty.<br/>";
$firstname = "";
}
if ($errMsg != "")
{
header("Location: fix_order.php?firstname=$firstname");
}
this is the code on fix_order.php where I want to access the variables.
$firstname = $_GET["firstname"];
echo "<p>firstname is $firstname .</p>";
I have tested the $firstname on the first page and it echo's the values just fine.
change your code to
$firstname = $_GET["errMsg"];
echo "<p>firstname is $firstname .</p>";
You can't access $firstname as this is the value not the key. errMsg is the key you should use.
Looks fine to me, it should work.
To get rid of the notice, you need to define variable by using isset()
$firstname = isset($_GET['firstname']) ? $_GET['firstname'] : '';
OR
if(isset($_GET['firstname'])) {
$firstname = $_GET['firstname'];
} else {
$firstname = '';
}

trying to compare two email fields - page blanks out

Right now, posting a snippet of what I wrote:
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
Every single time when I try to post the snippet above or a variation of it, it literally blanks out my page.
Question is, is the code I wrote above a good way to compare two email addresses via text fields?
And why does it blank out my entire page every time?
Here's a bit of further context if that's more helpful (let me know you want the entire page):
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nights"])) {
$nightsErr = "# of nights are required";
} else {
$nights = test_input($_POST["nights"]);
}
if (empty($_POST["arrivals"])) {
$arrivalsErr = "Time of arrival is required";
} else {
$arrivals = test_input($_POST["arrivals"]);
}
if (empty($_POST["male"])) {
$maleErr = "# of people (gender female) required";
} else {
$male = test_input($_POST["male"]);
}
if (empty($_POST["female"])) {
$femaleErr = "# of people (gender female) required";
} else {
$female = test_input($_POST["female"]);
}
if (empty($_POST["rooms"])) {
$roomsErr = "# of rooms required";
} else {
$rooms = test_input($_POST["rooms"]);
}
if (empty($_POST["type"])) {
$typeErr = "type of rooms required";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["name"])) {
$nameErr = "name required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "address required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["zip"])) {
$zipErr = "zip required";
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["telephone"])) {
$telephoneErr = "telephone required";
} else {
$telephone = test_input($_POST["telephone"]);
}
if (empty($_POST["email1"])) {
$email1Err = "email required";
} else {
$email1 = test_input($_POST["email1"]);
}
if (empty($_POST["email2"])) {
$email2Err = "email2 required";
} else {
$email2 = test_input($_POST["email2"]);
}
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is failing you and isn't the right syntax for what you want to achieve:
if (isset($_POST["email1"] != $_POST["email2"]))
What you need to do is to first check if it is set then check if both are (not) equal to, but it's best to use !empty(), then check if it is not equal to:
if (!empty($_POST["email1"]) && !empty($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "Emails don't match. Please enter the same email address.";
}
}
Plus, make sure your form elements both have the right name attributes.
Also, a blank page can mean syntax errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
What you are doing is assigning by using a single equals to sign rather make it a double equals to sign, I mean ==
Try:
if (isset($_POST["email1"]) && isset($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "please enter the same email address";
}
}

Call to a member function verifyInput() on a non-object

It seems like a pretty common problem but I can't see to find the answer to my problem. I have been getting the dreaded "Call to a member function verifyInput() on a non-object" fatal error.
<?php
// empty values
$name = $email = $topic = $message = "";
$nameErr = $emailErr = $topicErr = $messageErr = "";
// link the name tags in HTML
$name = $_POST['name'];
$email = $_POST['email'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
/* name if */
if (empty($_POST['name'])) {
$nameErr = " * Name is required";
} else {
$name = test_input($_POST["name"]);
}
/* email if */
if ( ! empty($_POST['email'])) {
if ($email->verifyInput($_POST['email'], 6)){
$fill['email'] = $_POST['email']; //$fill is the array of values passed
} else {
$emailErr = " * Email is incorrect - Try Again";
}
} else {
$emailErr = " * Email is required";
}
// Form content
$recipient = "generic#gmail.com";
$subject = "Contact Form";
$formcontent = "4 Days of Fun.ca -
\n\n\nFrom: $name \n\nEmail: $email \n\nSubject: $topic
\n\n\nMessage: $message";
$mailheader = "From: $email - Subject: $topic \r\n";
//function to send mail
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank you for contacting us, $name! \nWe will respond to you soon!";
}
//function for test_input
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// Validation of Inputs
function verifyInput($input, $type){
if ($type == 0) $pattern = '/^1$/';//just the number 1
elseif ($type == 1) $pattern = '/^[0-9]+$/';//just integers
elseif ($type == 2) $pattern = '/^[A-Za-zÁ-Úá-úàÀÜü]+$/';//just letters
elseif ($type == 3) $pattern = '/^[0-9A-Za-zÁ-Úá-úàÀÜü]+$/';//integers & letters
elseif ($type == 4) $pattern = '/^[A-Za-zÁ-Úá-ú0-9àÀÜü\s()\/\'":\*,.;\-!?&#$#]{1,1500}$/';//text
elseif ($type == 5) $pattern = '/^[A-Za-zÁ-Úá-úàÀÜü0-9\']+[A-Za-zÁ-Úá-úàÀÜü0-9 \'\-\.]+$/';//name
elseif ($type == 6) $pattern = '/^.+#[^\.].*\.[a-z]{2,}$/';//e-mail
elseif ($type == 7) $pattern = '/^((\(0?[1-9][0-9]\))|(0?[1-9][0-9]))?[ -.]?([1-9][0-9]{3})[ -.]?([0-9]{4})$/';//brazilian phone
if (preg_match($pattern, $input) == 1) return true;
else return false;
}
?>
This is where the error is in question:if ($email->verifyInput($_POST['email'], 6)){ however I'm confused... I looked it up and everywhere states that the variable passed in ie $email may not be an object. But the variable is declared as an object here: $email = $_POST['email']; is it not? Or am I missing something big and obvious?
I just started learning PHP but I've got a lot of foundational knowledge with C++, so there are a lot of similarities I already get... This is not one of them.
Maybe I'm just not understanding the -> operator, or maybe it's a non-object because of something else?
Thanks in advance.
$email->verifyInput() would call the method (function) verifyInput() that is included in the class email, but here i can see that your function is not a member of any class, so if you need to call this fuction you just have to change:
if ($email->verifyInput($_POST['email'], 6)){...
to:
if (verifyInput($_POST['email'], 6)){...
And regarding your question about ->:
As i mentioned above -> is used after the instantiated class followed by the member or the method name. probably you need to read more about PHP, i would suggest this course, or you can jump directly to get a course about PHP OOP right here.

PHP Simple Form Validation

Ok, what I'm trying to achieve is a very simple form validation like the following.
Name: [required, min length: 2, max length: 255]
Email: [required, min length: 3, max length: 255, valid email format]
Date of Birth: [optional, format: dd/mm/yyyy]
However, once i click submit (either if the fields are empty or filled) I get all of my echoed errors displayed on a blank page.
"name must be at least 2 charactersname is requiredemail must be at least 3 charactersinvalid emailemail cannot be left empty"
My code so far:
index.php
<form method="post" action="confirm.php">
Name:<input type="text" name="name" />
email:<input type="text" name="email" />
DOB:<input type="date" name="dob" />
<input type="submit" value="submit" />
</form>
and
confirm.php
<?php
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
$namelen = strlen($email);
$emaillen = strlen($email);
$max = 255;
$minname = 2;
$minemail = 3;
if($namelen<$minname){
echo"name must be at least 2 characters";
}
elseif($namelen>$max){
echo"name must be less than 255 characters";
}
if(empty($name)){
echo"name is required";
}
else{
continue;
}
if($emaillen<$minemail){
echo"email must be at least 3 characters";
}
elseif($emaillen>$max){
echo"email must be less than 255 characters";
}
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
continue;
}
else{
echo"invalid email";
}
if(empty($email)){
echo"email cannot be left empty";
}
else{
continue;
}
?>
Help would be greatly appreciated, thank you.
You have the following in your code:
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
You're basically trying to access undefined indexes. Remove the extra $ from the key names:
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
Then, further below, you have some conditions like this:
if(condition == true) {
continue;
} else {
// do something
}
It's actually not necessary, and you could change it to:
if(!condition) {
// do something
}
Also, it's better to push the error messages into an array ($errors) and then loop through it and display the error messages. It might help organize your code a bit better.
Here's how the modified code looks like:
if(!empty($_POST)) {
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$namelen = strlen($name);
$emaillen = strlen($email);
$max = 255;
$minname = 2;
$minemail = 3;
if($namelen < $minname){
$errors[] = "name must be at least 2 characters";
} elseif($namelen > $max){
$errors[] = "name must be less than 255 characters";
}
if($emaillen < $minemail){
$errors[] = "email must be at least 3 characters";
} elseif($emaillen > $max){
$errors[] = "email must be less than 255 characters";
}
if(empty($name)){
$errors[] = "name is required";
}
if(empty($email)){
$errors[] = "email cannot be left empty";
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errors[] = "invalid email";
}
echo "<ul>";
foreach ($errors as $error) {
echo "<li>$error</li>";
}
echo "</ul>";
}
It could still be improved, but however, this should get you started!
You have not written anything to make it stop after checking the first and second error.
Also, continue makes no sense in an if statement (see http://php.net/manual/en/control-structures.continue.php).
Lastly, the page is "blank" because there is no HTML output, just the text. You might want to redirect the user back to the form page with the error messages instead.
$name = $_POST['$name'];
$email = $_POST['$email'];
$dob = $_POST['$dob'];
That's wrong, you have to use
$name = $_POST['name'];
$email = $_POST['email'];
$dob = $_POST['dob'];
Also you may want to change the line
$namelen = strlen($email);
to
$namelen = strlen($name);
check if(!empty($_POST[fieldname]))
and then redirected it displaying a alert in javascript that the fields are empty

Select case with array

How can I write a select case with an array to check form validation?
this is my code:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$array = array($name,$email,$message);
switch($array[]) {
case empty($array[0]):
error = "name";
break;
case empty($array[1]):
error = "email";
break;
case empty($array[2]):
error = "message";
}
Then, I would like to write code to have this result:
if name is empty:
"Please fill in your name"
if email is empty:
"Please fill in your email"
if name and email is empty:
"Please fill your name and email"
if name and email and message is empty:
"Please fill in your name, email and message"
You want to concat your messages, so better use if statements:
$error = "Please fill in: ";
if (empty($array[0]))
$error .= "name ";
if (empty($array[1]))
$error .= "email ";
if (empty($array[2]))
$error .= "message ";
The .= will concat the string to the existing one.
Try this for a grammatically correct solution:
$empty = array();
$fields = array('name', 'email', 'message');
foreach ($fields as $key => $value){
if(empty($_POST[$value])) $empty[] = $value;
}
$error_msg = '';
$count = count($empty);
$cnct = ', ';
if ($count > 0){
$error_msg = 'Please fill in your ';
}
foreach ($empty as $key => $value){
if ($key == $count - 2){
$cnct = ' and ';
}elseif($key == $count - 1){
$cnct = '.';
}
$error_msg .= $value.$cnct;
}
You can simply try:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$error="Please fill in your ";
$array = array('name'=>$name,'email'=>$email,'message'=>$message);
foreach($array as $key=>$value){
if(empty($value)){
$error.=','.$key;
}
}
You can't use a variable expression in case statement of switch block.
A switch case must have a constant expression in many languages including php. So, something like a variable or function call doesn't work.
You better use conditionals for this.
Your code is also missing $ symbol for variable error.
Do this instead:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$array = array($name,$email,$message);
$error="Please fill in your ";
if(empty($array[0])){
$error.= "\nname";
}
if(empty($array[1])){
$error.="\nemail";
};
if(empty($array[2])){
$error.= "\nmessage";
}
echo $error;
You should simply write:
$error = "Please fill in: ";
if (empty($array[0]))
$error.= "name ";
if (empty($array[1]))
$error.= "email ";
if (empty($array[2]))
$error.= "message";
A switch isn't made for what you want to do.

Categories