if else statements php - php

How do I get this to not display when you first go to the page???
if ($error) {
echo "Error: $error<br/>";
}
if ($keycode) {
echo "Keycode: $keycode<br/>";
}

<?php
session_start();
if ($_SESSION['been_here'] == true) {
// show what you need to show
}
else {
// don't show it
$_SESSION['been_here'] = true;
}
?>
The point here is that $_SESSION-variables "last" (as long as you session_start()).
Google "php sessions" for more information, and ask more questions on SO if necessary. :)
Use session_destroy(); to destroy the session.

<?php
if ($error){ echo "Error: $error
"; } if ($keycode) { echo "Keycode: $keycode
"; }

Based on the comments, it seems that your conditional is evaluating to true before you expect it to. Without seeing more of your code, this is only a guess, but I believe your problem is that you're giving the variable $error a default/temporary value when you create it that doesn't mean false. For example:
$error = "default error message, change me later";
// Later...
if ($error) { // This evaluates to true
echo "Error: $error<br/>";
}
If so, you'll want to check out PHP's documentation on casting to booleans, and maybe use something like this (with contribution from Christian's answer):
$error = "0"; // Default error message, change it later
// Later...
if($_SESSION['been_here'] == true)
$error = "This is the real error message.";
// Even later...
if ($error) {
echo "Error: $error<br/>";
}

This probably works for you:
if (isset($error) && !empty($error)) {
echo "Error: $error<br/>";
}
I cannot say more, because you have not specified what the value of $error might be.
Or you just have to introduce a flag that indicates that an error occurred:
$error = 'Error message.';
$has_error = false;
if(!empty($_POST) && some_condition) { // means it is a POST request
$has_error = true;
}
if($has_error) {
echo "Error: $error<br/>";
}

Related

Stop PHP Execution But Display HTML

In a Profile page of the User, I want to validate his input with PHP after submission and display errors on the same page before updating in the database.
For this, I'm doing something like:
<div>
<?php
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
echo "<p>Please enter a valid email address.</p>";
return; // or exit;
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
echo "<p>Please enter a valid phone number.</p>";
return; // or exit;
}
...
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
echo "<p>An error occurred! Could not update your profile information!</p>";
}
}
?>
</div>
<my-footer></my-footer>
So when an error occurs upon PHP validation, the footer doesn't appear. So I understood that with return or exit the page will stop rendering at that command.
What can I do to solve this issue?
I want it to stop execution of the PHP script but display the rest of the HTML page.
You could put your validation logic inside a function at the top of your page, and change all your echo to return.
function validate() {
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
return "<p>Please enter a valid email address.</p>";
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
return "<p>Please enter a valid phone number.</p>";
}
//...
if (updateUser($id, $email, $phoneNumber, $name)) {
return "<meta http-equiv='refresh' content='0'>";
} else {
return "<p>An error occurred! Could not update your profile information!</p>";
}
}
}
Then simply echo the string returned from the function above the footer.
<div>
<?php echo validate(); ?>
</div>
<my-footer></my-footer>
Note that the above will work because $_POST is a superglobal. However, you may consider changing your function to pass email, phoneNumber, name and id as parameters instead.
Change your flow up a little bit...
if (isset($_POST["submitted"])) {
$has_errors = FALSE;
$err_msg = '';
if (!isValidEmail($_POST["email"])) {
$err_msg .= "<p>Please enter a valid email address.</p>";
$has_errors = TRUE;
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
$err_msg .= "<p>Please enter a valid phone number.</p>";
$has_errors = TRUE;
}
if ( $has_errors ) {
echo "<p>Please Correct the following and resubmit...</p>" . $err_msg;
} else {
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
echo "<p>An error occurred! Could not update your profile information!</p>";
}
}
}
Many times you will see PHP frameworks that can handle this for you.
Here's a good website to compare a few: http://phpframeworks.com/
But what you can do is put your footer (and / or the rest of your code) into a function that holds the rest of your code for you, and you can call it later or whenever you need to so you can still end code execution gracefully.
<div>
<?php
function footer() {
$string = "</div>";
$string .= "<my-footer></my-footer>";
return $string;
}
if (isset($_POST["submitted"])) {
if (!isValidEmail($_POST["email"])) {
echo "<p>Please enter a valid email address.</p>";
die(footer()); // Displays footer
}
if (!isValidPhoneNumber($_POST["phoneNumber"])) {
echo "<p>Please enter a valid phone number.</p>";
die(footer()); // Displays footer
}
...
if (updateUser($id, $email, $phoneNumber, $name)) {
echo("<meta http-equiv='refresh' content='0'>");
} else {
die("<p>An error occurred! Could not update your profile information!</p>" . footer()); // kills the page execution, but still returns the foot of the page.
}
}
echo footer();
?>

Trying to get Unique entries set right for my form

so I have searched this problem and found similar ones, but I'm not sure of how to translate their solutions into mine - mainly because I'm a noob in PHP. I'm working on it. Bear with me. I appreciate the help!
Right now, I am trying to make it so my form will not allow duplicate entries for the email column in phpmysql. So far, I went into the structure tab there, and made it unique. Pretty much viola. However, I would like the error message to display on the same page when the form is submitted, instead of reloading it and giving the message. Also, I would like to customize the message. Seeing as its a phpmysql related error, I'm not sure if I would do that with PHP coding, or somewhere in there.
Thanks guys. I appreciate the help.
<?php
function checkField($v){
return (isset($v) && $v === false) ? true: false;
}
function startMysql(){
$con=mysqli_connect("localhost", "shiftedr_admin", "passwerd", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
return null;
}
return $con;
}
// function closeMySql($connection){
// mysqli_close($connection);
// }
function formcheck(){
$con=mysqli_connect("localhost", "shiftedr_admin", "shithead1", "shiftedr_whosthedeeusers");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
if (isset($_POST['submitted'])){
$form = null;
if (empty($_POST['fullname'])){
$form['fullnameflag'] = false;
}
if (empty($_POST['email'])){
$form['emailflag'] = false;
}
if (empty($_POST['password'])){
$form['passwordflag'] = false;
}
if (empty($_POST['pwc'])){
$form['pwcflag'] = false;
}
if (empty($_POST['userbday'])){
$form['userbday'] = false;
}
if (empty($_POST['gender'])){
$form['genderflag'] = false;
}
if ($_POST['password'] != $_POST['pwc']){
$form['fixpasswordconfirm'] = false;
}
/*$query = mysql_query ("SELECT * FROM users2 WHERE email = '". Email'" ."'");
if (mysql_num_rows($query) > 0)
{
echo 'Email Address is Already In Use.';
}*/
if (empty($form)) { // all fields correct at this point, do database stuff
$sql="INSERT INTO Users2 (fullname, Email, Password, userbday, Gender) VALUES ('".$_POST['fullname']."','".$_POST['email']."','".$_POST['password']."','".$_POST['userbday']."','".$_POST['gender']."')";
if (!mysqli_query($con,$sql)){
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
}
}
mysqli_close($con);
return $form;
}
}
//// / include("myfunctions.php");
?>
I am guessing you have two pages - myform.php and process.php or something similar so try doing this
<?php
$error = null;
if( isset( $_POST['submitted'] ) ) // Same as your check is submitting if
{
// Below is an example fail
if( empty( $_POST['fullname'] ) ) $error = 1;
// So for the email address failing you would put
if( mysql_num_rows($query) > 0 ) $error = 2;
if(! $error )
{
// all good no errors here so do database stuff....
}
else
{
header("Location: form.php?error=$error"); // return the error code to previous page
}
}
?>
Were one could be an empty field or could be fullname is empty and two is used email address or something similar and on your myform.php page have
<?php
if( isset( $_GET['error'] ) )
{
switch ( $_GET['error'] )
{
case 1 : echo "One of the fields is empty"; break;
case 2 : echo "Your email address has already been used"; break;
default : echo "Unknown error occured";
}
}
?>

Validate Email Error

<?php
if (isset($_POST['ign'], $_POST['email'])) {
if($_POST['ign'] && $_POST['email']){
}
else {
echo ("Please enter all of the values!");
}
}
else {
echo ("Error in form data!");
}
if((FILTER_VALIDATE_EMAIL($_POST['email'] == TRUE))) {
$email = $_POST['email'];
echo ("Thanks, " . htmlentities($_POST['ign']) . ", you will recieve an email when the site is complete!");
}
else {
echo "Failure!";
}
// insert email and ign into database
?>
Is this going to work correctly? First time doing something completely from scratch lol!
OK! I have changed it. What about this? Should I also do the empty thing?
<?php
if (!isset($_POST['ign'], $_POST['email'])) {
if($_POST['ign'] && $_POST['email']){
echo "Please fill out all of the fields!";
die;
}
if(var_filter($_POST['email'], FILTER_VALIDATE_EMAIL))
$email = $_POST['email'];
echo ("Thanks, " . htmlentities($_POST['ign']) . ", you will recieve an email when the site is complete!");
}
else {
echo "Your email was invalid!";
}
// insert email and ign into database
?>
Use built in functions, don't re-invent the wheel:
if(filter_var($mail, FILTER_VALIDATE_EMAIL)){
echo "Mail is valid!";
}
WHY IS YOUR FUNCTION NAME ALL CAPS?
...and do you see the difference between this...
if(func($_POST['email'] == TRUE)){
and this..
if(func($_POST['email']) == TRUE){
?
There are lots of mistakes there. Here's what you should be doing:
// First check if both fields are present. Usually there is no point in doing this
// because the next check will also catch this case, but you had it so I put it in too.
if (!isset($_POST['ign'], $_POST['email'])) {
echo ("Error in form data!");
die; // or something else
}
// Then check if both values are non-"empty" (you might want to look at the docs for
// an explanation of what this means exactly).
if (empty($_POST['ign']) || empty($_POST['email'])) {
echo ("Please enter all of the values!");
die; // or something else
}
// Finally, validate the email. DO NOT COMPARE WITH true!
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo "Failure!";
die; // etc
}
echo ("Thanks, " . htmlentities($_POST['ign']) . ", blah blah!");

if !isset multiple OR conditions

I cannot get this to work for the life of me, it is PHP.
<?php
if (!isset($_POST['ign']) || ($_POST['email'])) {
echo "Please enter all of the values!";
}
else {
echo "Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is complete!";
}
?>
I've also tried using !isset twice.
isset() accepts more than just oneparameter, so just pass as many variables as you need to check:
<?php
if (!isset($_POST['ign'], $_POST['email'])) {
echo "Please enter all of the values!";
}else{
echo "Thanks,". $_POST['ign'].", you will receive an email when the site is complete!";
}
?>
You could use empty() as well, but it doesn't accept more than a variable at a time.
This is how I solved this issue:
$expression = $_POST['ign'] || $_POST['email'] ;
if (!isset($expression) {
echo "Please enter all of the values!";
}
else {
echo "Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is
complete!";
}
Simplest way I know of:
<?php
if (isset($_POST['ign'], $_POST['email'])) {//do the fields exist
if($_POST['ign'] && $_POST['email']){ //do the fields contain data
echo ("Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is complete!");
}
else {
echo ("Please enter all of the values!");
}
}
else {
echo ("Error in form data!");
}
?>
Edit: Corrected the code to show the form data and empty values errors seperatly.
Explanation: The first if statement checks that the submitted form contained two fields, ign and email. This is done to stop the second if statement , in the case that ign or email weren't passed in at all, from throwing an error(message would be printed to server logs). The second if statement checks the values of ign and email to see if they contain data.
Try this:
<?php
if (!isset($_POST['ign']) || isset($_POST['email'])) {
echo "Please enter all of the values!";
}
else {
echo "Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is complete!";
}
?>
isset($_POST['ign'],$_POST['email']));
and then check for the empty values.
When you work with POST, use empty(). because when your form send data. It async null for empty input!
best way is that:
if ((!isset($_POST['ign']) || empty($_POST['ign'])) &&
(!isset($_POST['email']) || empty($_POST['email'])) {
YES! It's Ugly...
So you can use:
<?php
if ( checkInput($_POST['ign']) || checkInput($_POST['email']) ) {
echo "Please enter all of the values!";
}
else {
echo "Thanks, " . $_POST['ign'] . ", you will recieve an email when the site is complete!";
}
function checkInput($input){
return ( !isset($input) || empty($input) );
}
?>
You can try this code:
<?php
if(!isset($_POST['ign'], $_POST['email'])) {
echo "Please enter all of the values!";
} else {
echo "Thanks, " . $_POST['ign'] . ", you will receive an email when the site is complete!";
}
?>
// if any of this session is set then
if (isset($_SESSION['tusername']) || isset($_SESSION['student_login'])) {
it will return true;
} else {
it will return false;
}

PHP and Function Errors

I was looking to see what would be the best way to handle errors from functions. Is the "DIE" method appropriate?
ie. php function calls another, for example:
function login(){
$result = verifyDetails("bob", "password123");
if($result == "accepted"){
echo "Welcome bob";
}else{
echo "Error!! \n";
echo $result;
}
}
function verifyDetails($user, $pass){
if(empty($user) || empty($pass)){
die("cannot be empty");
}
if($user == "bob" && $pass == "password"){
return "accepted";
}else{
die("username or password incorrect");
}
}
does the "DIE" method return the message or does everything come to a standstill?
thanks in advance
UPDATE
what if the output is not known?
for example. in the above example I have placed "accepted" as the only correct answer.
What if the return is a name or id number.. then you cant really separate the error and correct returns.
thanks again.
UPDATE / Possible Solution
function login(){
$result = verifyDetails("bob", "password123");
if($result[0] == "SUCCESS"){
echo "Welcome bob";
}else if($result[0] == "ERROR"){
echo "Error!! \n";
echo $result;
}else{
echo "Unknown Error!!";
}
}
function verifyDetails($user, $pass){
$msg = array();
if(empty($user) || empty($pass)){
$msg[0] = "ERROR";
$msg[1] = "cannot be empty"
return $msg;
}
if($user == "bob" && $pass == "password"){
//say $customerID is extracted from a db
$msg[0] = "SUCCESS";
$msg[1] = $customerID
return $msg;
}else{
$msg[0] = "ERROR";
$msg[1] = "username or password incorrect"
return $msg;
}
}
ideas & suggestions on the above "possible" solution are welcome
UPDATE
Check Shikiryu update 2 answer below for a cleaner version using arrays
die() just echo your message and stop the script because die() is an alias of exit().
In your case, since the password isn't password but password123, the script will stop just displaying "username or password incorrect".
But as I can see here, you want a return "cannot be empty";, so that it'll display :
Error!!
username or password incorrect
(and optionally the rest of the html which die() won't)
Update 2 (ugly way) :
function login(){
$result = verifyDetails("bob", "password123");
if(isset($result['success']){ // verifyDetails return true?
echo $result['success'];
}else{
echo "Error!! \n";
echo $result['error']; // Display the error verifyDetails throws
// You may want to check if $result['error'] exists.
}
}
function verifyDetails($user, $pass){
if(empty($user) || empty($pass)){
return array('error'=>"cannot be empty");
}
if($user == "bob" && $pass == "password"){
return array('success'=>"Welcome bob");
}else{
return array('error'=>"username or password incorrect");
}
}
die terminates the execution of the PHP script at the line it is called. Therefore, your message would no be returned.
You might want to simply use return instead of die;
Yes, you could use die() to debug.
does the "DIE" method return the message or does everything come to a standstill?
Yes, it returns the error message and yes, the script will stop continuing.
Well the only acceptable way in your case is return FALSE
if these functions are really methods of some class, use class variable to store actual errors.
if these functions belongs to no class, I wouldn't use them at all, but write it in plain code
if($user == "bob" && $pass = "password"){
echo "Welcome bob";
}else{
echo "incorrect username or password");
}
updated answer
Well there is nothing to invent. Just follow the way PHP goes:
Make your function return either value or FALSE
however, for the validation purpose you have to make it this way:
function validSomething($val){
return (bool)rand(0,1);
}
$err = array();
if (!validSomething($var)) {
$err[] = "Whatever error";
}
i.e. function returns only boolean values and actual error message being added by application logic.
However, in your example user-defined functions are totally misused.

Categories