Changing the value of a variable php - php

I need to change the value of the variable $destination to help validate a form. If none of the fields within the form, the page refreshes with the error message displayed, which works. If the fields are all filled in, the the $destination value should change and the message 'it works!' is printed. However, if all fields are filled in and the user submits the form, the message 'it works!' is printed, but the $destination's value is still set to 'this-page'. What am I missing here?
$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!$fname OR !$lname OR !$email OR !$phone) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}

Hope this is academic. There are better ways to approach this. But here:
$destination = '';
$fname = isset($_POST['fname']) ? $_POST['fname'] : null ;
$lname = isset($_POST['lname']) ? $_POST['lname'] : null ;
$phone = isset($_POST['phone']) ? $_POST['phone'] : null ;
$email = isset($_POST['email']) ? $_POST['email'] : null ;
if (empty($fname) || empty($lname) || empty($phone) || empty($email)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
} else {
print 'It works!';
$destination = 'results-page';
}
Someday take a look at some PHP frameworks and how they handle form validation. for example: http://framework.zend.com/manual/1.12/en/zend.form.elements.html Might give you some insight.

$destination = '';
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$email = $_POST['email'];
if (!empty($fname) || !empty($lname) || !empty($email) OR !empty($phone)) {
print 'Please fill in all of your contact information';
$destination = 'this-page';
}
else {
print 'It works!';
$destination = 'results-page';
}

Seems like the problems isn't related to the validation part here. You are getting both the print from the else statement and the $destination variable from the if statement? That should be logically impossible. Are you sure you don't have any syntax errors etc. in your code? Is that the exact code you have in your program?

Related

How to end PHP process if variable is blank/null

I have a form submission page that POSTS the fields to a confirmation page that sends an email using PHP but I keep getting blank emails when the page is ran as a stand alone page instead of from the form submission page. The form has 'required', but I want to add a statement to the PHP that stops the process if the $email variable is blank/null.
<?php
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = "Thank you for registering you team";
$message = "<html>...
In addition to stopping the process if the $email variable is blank/null, I also want to redirect the user to our home page.
You should be able to do something like this:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['email'])) {
// variables start
$team = $_POST['team'];
$manager = $_POST['manager'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$city = $_POST['city'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$classification = $_POST['classification'];
$registration = $_POST['registration'];
$division = $_POST['division'];
// variables end
// email start
$subject = 'Thank you for registering you team';
$message = '<html>...';
} else {
header('Location: https://example.com');
}
Simplest way:
...
// variables end
if( ! (!isset($email) || trim($email) === '') ){
header("Location: homepage.php");
exit();
}
// email start
...
Note the exit() statement after the redirection: without exit() or die() the PHP script could be continue the execution resulting in possible unexpected behaviour.

empty of php doesn't catch empty string

I'm confused how to use isset and empty, I'm trying to write a simple api, there should be error saying which param is missing and return error too if the param is null.
What's wrong my statement below?
$email= isset($_POST['email']) ? mysqli_real_escape_string($mysqli, $_POST['email']) : '';
if(empty($email)) {
echo 'email cannot be empty!'
}
You don't actually need to use both isset and empty, because empty already does it.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
More details are here:
http://php.net/manual/en/function.empty.php
So your code could look this way, for example:
if (empty(trim($_POST['email']))) {
echo "Email cannot be empty!\n";
// you should add return or raise exception here
// or even exit
exit;
}
$email = trim($_POST['email']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Your email {$email} is invalid\n";
// you should add return or raise exception here
// or even exit
exit;
}
$email = mysqli_real_escape_string($email);
Change $email to :
$email= isset($_POST['email']) && !empty($_POST['email']) ? mysqli_real_escape_string($mysqli, $_POST['email']) : '';
So the $_POST['email'] is not containing empty value.
Try to use next code snippet
if( false === input_filter(INPUT_POST, FILTER_VALIDATE_EMAIL) ) {
echo "error message";
}
$email = input_filter(INPUT_POST, FILTER_SANITIZE_EMAIL );
// to do somethink with email...
I think you are trying to check $email value which is null. You should check $fname in if statement instead.
try this to check for all missing fields:
$required_fields = array('email', 'name', 'password');
$err_msgs=array();
foreach($required_fields as $field) {
if(empty( $_POST[$field]) ){
err_msgs[]= $field . ' cannot be empty!';
}
}
if (!empty($err_msgs)) {
echo json_decode($err_msgs);
}
Edit: removed isset() after reading Axalix's answer.

PHP error posting form data to database

I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!
<?php
session_start();
include'db.php';
$name = $_POST['name'];
$email = $_POST['email'];
$phoneNumber = $_POST['mobile-num'];
$photos = $_POST['fileselect'];
$town = $_POST['location'];
$category = $_POST['category'];
$adTitle = $_POST['title'];
$adDescription = $_POST['description'];
if(isset($_SESSION['email']))
{
if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
{
$name = stripslashes($name);
$email = stripslashes($email);
$phoneNumber = stripslashes($phoneNumber);
$photos = stripslashes($photos);
$town = stripslashes($town);
$adTitle = stripslashes($adTitle);
$category = stripslashes($category);
$adDescription = stripslashes($adDescription);
$name = mysqli_real_escape_string($connection,$name);
$email = mysqli_real_escape_string($connection,$email);
$phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
$photos = mysqli_real_escape_string($connection,$photos);
$town = mysqli_real_escape_string($connection,$town);
$adTitle = mysqli_real_escape_string($connection,$adTitle);
$category = mysqli_real_escape_string($connection,$category);
$adDescription = mysqli_real_escape_string($connection,$adDescription);
$imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
$photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
$date = date("j F Y");
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
header("Location: /profile.php");
}
else
$_SESSION['errorMessage'] = "Please check email pattern";
header("Location: /post-ad.php");
}
else
$_SESSION['errorMessage'] = "Please input all the required details";
header("Location: /post-ad.php");
}
else
header("Location: /login.php");
?>
That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form
Not sure why you are running the SELECT, as you seem to do nothing with it and no parameters. But the INSERT should be...
$insertQuery = mysqli_query($connection, "INSERT INTO ads(email,`ad-title`,`ad-category`,`ad-description`,`Photos`,`Name`,`Mobile-Num`,`Town`,`date`)
VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
When you have column names with hyphens in them it should be enclosed in back-ticks, either that of I would recommend (if not tooo late ) to remove the hyphens and use an underscore instead.
You should also check for errors when running any SQL and do some sort of processing with them.
Thanks Guys for the help. Sorry for putting you all through the stress. I went through my database structure and found a column with the wrong type that was preventing the sql insert query. My apologies....

how to make this if else in ternary operator

I am looking for email in my view page. there are two ways email can get there. Either by POST or by SESSION.
if it is a $_POST then I want to use the $_POST email other wise I want to use the email saved in session.
Currently the code I have is below
$email = (isset($_POST['email']) ? $_POST['email'] : '');
whats the BEST way to do it in least lines of code
I'm guessing you're just looking for this (assuming the email address is stored in the $_SESSION array under the key email):
$email = (isset($_POST['email']) ? $_POST['email'] : $_SESSION['email']);
Or am I misunderstanding your question?
Try this:
$email = (isset($_POST['email']) ? $_POST['email'] : (isset($_SESSION['email'])) ? $_SESSION['email'] : '');
Which is the same of:
if(isset($_POST['email'])) {
$email = $_POST['email'];
} else {
if(isset($_SESSION['email'])) {
$email = $_SESSION['email'];
} else {
$email = '';
}
}
A funny alternative to the correct answer of #Gabriel Santos
$input = function($param, $default = '') {
static $input;
if (null === $input) {
$input = array_merge($_SESSION, $_POST);
}
return isset($input[$param]) ? $input[$param] : $default;
};
// get input
$email = $input('asd');

PHP Form Inserting to MySQL NULL Values Allowed

I have a form which submits to a php file which inserts data to a table in MySQL there a some fields in this form which may not be filled in and if this is the case the record doesn't get inserted even though I have set the field in MySQL to accept nulls
My Code
<?php
session_start();
include "includes/connection.php";
$title = $_POST['inputTitle'];
$firstname = $_POST['inputFirstname'];
$lastname = $_POST['inputLastName'];
$address1 = $_POST['inputAddress1'];
$address2 = $_POST['inputAddress2'];
$city = $_POST['inputCity'];
$county = $_POST['inputCounty'];
$postcode = $_POST['inputPostcode'];
$email = $_POST['inputEmail'];
$homephone = $_POST['inputHomephone'];
$mobilephone = $_POST['inputMobilephone'];
$userid = $_POST['inputUserID'];
if($title == '' || $firstname == '' || $lastname == '' || $address1 == '' || $address2 == '' || $city == '' || $county == '' || $postcode == '' || $email == '' || $homephone == '' || $mobilephone == '' || $userid == ''){
$_SESSION['status'] = 'error';
} else {
mysql_query("INSERT INTO contact
(`id`,`user_id`,`title`,`firstname`,`lastname`,`address1`,`address2`,`city`,`county`,`postcode`,`email`,`homephone`,`mobilephone`)
VALUES(NULL,'$userid','$title','$firstname','$lastname','$address1','$address2','$city','$county','$postcode','$email','$homephone','$mobilephone')") or die(mysql_error());
$_SESSION['status'] = 'success';
}
header("location: contacts.php");
?>
can anyone tell me what I need to change to sort this issue out?
Best
Justin
P.s sorry if the code block is a bit long but I think it is relevant in this question.
You should change your assignement (for the null-able columns), like
$title = empty( $_POST['inputTitle'] )
? 'NULL'
: "'" . mysql_real_escape_string( $_POST['inputTitle'] ) . "'"
;
And in your query you have to remove the quotes around the variables.

Categories