php check if two variables are empty and merge them togheter - php

First thing first, i'm new to php.
I'm trying to check if two variables are both empty, and if so merge them togheter to display only one result, but if one of them is not empty, than i have to display is value.
I currently have:
$customerNotesWC = "";
$DYSPrintableOrderNotes = "test note";
Here's the code i tried so far:
function displayCustomerOrderNotes($customerNotesWC,$DYSPrintableOrderNotes){
if ($customerNotesWC == "") {
$customerNotesWC = "(none)";
}
if ($DYSPrintableOrderNotes ==""){
$DYSPrintableOrderNotes = "(none)";
}
if ($DYSPrintableOrderNotes == "(none)" && $customerNotesWC == "(none)"){
$NotesToDisplay = "(none)";
}
else {
$NotesToDisplay = $customerNotesWC . "<br/>" . $DYSPrintableOrderNotes;
}
}
Unfortunately this doesn't work, as the results is the following:
(none)
Pre-sale order note
I know that there must be a better way to achieve this, and any suggestions will be really appreciated.
Thanks a lot

In order to get your desired functionality of only printing "(none)" when both values are blank, the simplest thing to do to fix your code is remove the code that's setting either value to "(none)" and change your main if-statement to check for "":
function displayCustomerOrderNotes($customerNotesWC,$DYSPrintableOrderNotes){
if ($DYSPrintableOrderNotes == "" && $customerNotesWC == ""){
$NotesToDisplay = "(none)";
}
else {
$NotesToDisplay = $customerNotesWC . "<br/>" . $DYSPrintableOrderNotes;
}
//shouldn't there be an echo $NotesToDisplay; or return $NotesToDisplay; ? or something?
}

Related

Get Isset Variable to Specific Value

if (isset($data['start']['tan']) AND $data['start']['tan'] == true) {
$get_data[] = 'tan';
}
if (isset($data['start']['ban']) AND $data['start']['ban'] == true) {
$get_data[] = 'ban';
}
if (isset($data['start']['pan']) AND $data['start']['pan'] == true) {
$get_data[] = 'pan';
}
Try to take only tan equal to "a111" values. Tested the code below, but I could not get even tan values.
if (isset($data['start']['tan']) AND $data['start']['tan'] == true AND $data['start']['tan'] == 'a111') {
$get_data[] = 'tan';
}
Have you tried to debug this yourself? Is it possible that the data you are looking for is not in the $data variable? Or that it's in a different format?
Try adding this:
print_r($data)
before your IF statements to help you debug the issue. Your code MOSTLY looks correct. Though, I know that I have always used .= when potentially appending to arrays, instead of just = . Like:
$get_data=array();
if ($tan) $get_data[] .= $data;
Of course, I was generalizing in my above example, but you get the idea.

HTML Registration Form - Array not treated as empty()

Heyo newbie to PHP here,
I'm creating a registration form where the user is able to select how many family members are in the family, Depending on the number selected the same number of fields would be created to allow them to enter family members' details.
The form checks if all error messages are empty before starting the database insert.
I've been trying for hours though still not sure what's causing the array to return empty() - False,
Full Code -
GDrive Share Link
Creation of the Arrays
$MemberNameErr = array();
$MemberDOBErr = array();
Giving the Array values based on the number of Family Members
for($Variable_Counter = 0; $Variable_Counter < $Family_Counter;
$Variable_Counter++)
{
$MemberNameErr[$Variable_Counter] = "";
$MemberDOBErr[$Variable_Counter] = "";
}
If function that checks that no errors have been made
if ($FamilyNameErr == "" && $DateErr == "" && $EmailErr == "" && $PhoneErr == "" && $MobileErr == "" && empty($MemberNameErr) && empty($MemberDOBErr))
{
currently using empty() as a way to check if the array is empty
created these just to check if the arrays were Not Empty
if (!empty($MemberNameErr))
{
echo " MEMBER ERROR NOT EMPTY ";
}
if (!empty($MemberDOBErr))
{
echo " DOB ERROR NOT EMPTY ";
}
Thank you for all your input.
In your loop
for($Variable_Counter = 0; $Variable_Counter < $Family_Counter; $Variable_Counter++)
{
$MemberNameErr[$Variable_Counter] = "";
$MemberDOBErr[$Variable_Counter] = "";
}
You're assigning empty string to indexes of the array. This means the array isn't empty anymore.
In example :
$tab = array("", "", "");
if (empty($tab))
{
echo "Empty";
}
else
{
echo "Not empty";
}
Output :
Not empty
A workaround could be to iterate through this array and check if there's at least 1 non empty string.
In example
function CheckNonEmptyValue($arr)
{
foreach ($arr as $value)
{
if (!empty($value))
{
return (true);
}
}
return (false);
}
if (CheckNonEmptyValue($MemberNameErr))
{
echo " MEMBER ERROR NOT EMPTY ";
}
if (CheckNonEmptyValue($MemberDOBErr))
{
echo " DOB ERROR NOT EMPTY ";
}

if statement when NULL (PHP)

I want to have if the variable = null then he makes it to 1.
if the variable exist do nothing and dont make it again to 1.
i got this code:
if (isset($_POST["register"])) {
if(!$l_NextPage){
$l_NextPage = 1;
echo "helaas" . "</br>";
}
if($l_NextPage == 1){
echo "hoi";
$l_NextPage = 2;
}else if($l_NextPage == 2){
echo "doei";
}
}
only the code dont work i tried empty, isset, $var == FALSE but everytime he makes $l_NextPage to 1. is there any solution i tried this too with session but even it don't work!
What am I doing wrong?
what happen when you refresh page, it assign $l_NextPage = 1 every time, thats why all the time hoi printed
you can use sessions for preserving value of variable after page refresh
try this code
// write this line of code at top of php block
session_start();
if (isset($_POST["register"]))
{
if (!isset($_SESSION["l_NextPage"]))
{
$_SESSION["l_NextPage"] = 1;
echo "helaas" . "</br>";
}
if($_SESSION["l_NextPage"] == 1)
{
echo "hoi";
$_SESSION["l_NextPage"] = 2;
}
else if($_SESSION["l_NextPage"] == 2)
{
echo "doei";
//unset( $_SESSION['l_NextPage'] ); unset varibale
}
}
after reaching at prefixed condition you can unset varible using
unset( $_SESSION['l_NextPage'] );
i have not tested code but this should work
you should try:
if(!isset($l_NextPage)) {
$l_NextPage = 1;
echo "helaas" . "</br>";
}
elseif($l_NextPage == 1) {
(...)
try like this,
if(!empty(trim($l_NextPage)))

PHP replacing blank images with a default one

Having one of those brain fade moments this morning. I have the following php:
$imgset = $result->fields[6];
if ($imgset = '')
{
$imgset = 'logo';
}
else
{
$imgset = $result->fields[6];
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
$imgset = '';
Where it looks to see if the result from the database is blank and if so, should put in logo.jpg instead of whatever the result is. For some reason though, it just does not want to work and I am probably being completely blind, but cannot see why not. I still get blank images in the HTML and filenames of "/img/.jpg" as though $imgset is still passing through a blank. The values are not NULL in the SQL either, they are most definitely blank entries inputted from an inputbox using a _POST in a form elsewhere.
This:
if ($imgset = '') {
Is always setting $imgset to empty. Use comparison instead:
if ($imgset == '') {
Your else is also not needed since in that case $imgset is already set as $result->fields[6];.
Try to verify if the image exists in your path as well
<?php
$imgset = $result->fields[6];
if ($imgset) {
$imgset = $result->fields[6];
$path ='pathtoimages';
if(!file_exists($path.'/'.$imageset.'.jpg'){
$imgset = 'logo';
}
}
else
{
$imgset = 'logo';
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
?>
You forgot to compare on the if condition and instead you are assigning an empty value to $imgset. if ($imgset = '') should be if ($imgset == '')
$imgset = $result->fields[6];
if ($imgset == '')
{
$imgset = 'logo';
}
echo '<img id="imgdisp" src="/img/'.$imgset.'.jpg" />';
$imgset = '';
you do not need the else part as the value is already assigned in the first statement.
Using a ternary operator it can be done like this:
echo '<img id="imgdisp" src="/img/'.(empty($imgset)?'logo':$imgset).'.jpg" />';
Shorter code at the cost of readability.
This is the reason why it's better to reverse the condition:
if ('' = $imgset)
would have lead to an error.
The answer:
if ('' == $imgset)
//or
if (empty($imgset))
If you are selecting from MYSQL, you can use something like
SELECT *,COALESCE(image,"logo") AS image FROM ....
This way when the results come back and some rows have a NULL image, it will be replaced by "logo" so you don't need the IF logic in your PHP :)

Dynamic if-statement with variables?

I'm trying to create a dynamic if-statement. The reason I want to do this, is because I need to check server-sided whether inputfields match my regex and are not empty. However, some of my inputfields can be removed in my CMS, meaning there would be more/less inputfields accordingly.
Ideally I would add variables in my if-statement but I'm not 100% sure if that's allowed, so perhaps I would need an other way to solve this problem. Here's what I tried:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = " || $_POST['streetname'] == ''"; //Used to check if field is empty
$pstreetname = " || !preg_match($streetnameReg,$_POST['streetname'])"; //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = ''; //Not needed in check
$pstreetname = ''; //Also not needed in check
}
// more of these if/else statements
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' $cstreetname $cpostalcode $chometown $ctelnr $csex $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
else
{
//Regex check, after that more code
}
My idea was to check if a specific field is shown on the front-end and in that case I'm creating some variables that I want to paste in my if-statements.
I'm getting an error saying Server error meaning my php-code would be invalid.
Is it even possible at all to make a dynamic if-statement? If yes, at what part am I failing?
Help is much appreciated! Thanks in advance.
First of all, since it looks like you need to combine all of the conditionals with ||, you can correct your program by writing it like this:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = $_POST['streetname'] == ''; //Used to check if field is empty
$pstreetname = !preg_match($streetnameReg,$_POST['streetname']); //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = false; //Not needed in check
$pstreetname = false; //Also not needed in check
}
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' || $cstreetname || $cpostalcode || $chometown || $ctelnr || $csex || $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
This would work, but it's unwieldy. A much better solution would be to use an array (let's name it $errors that gets dynamically populated with errors resulting from validating your fields. Like this:
$errors = array();
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
if ($streetname == '') {
$errors[] = 'Streetname cannot be empty.'; // message is optional
}
if (!preg_match($streetnameReg,$streetname)) {
$errors[] = 'Streetname is invalid.'; // message is optional
}
}
And then:
if ($errors) {
echo 'There are errors with the data you submitted.';
header('refresh:3;url=index.php');
}
If you provided human-readable error messages you can also arrange for them to be displayed so that the user knows what they need to fix. And of course there are lots of variations of this technique you can use -- e.g. group the error messages by field so that you only show one error for each field.
If you want to check for empty $_POST fields you can do something like this
$error = False;
foreach($_POST as $k => $v)
{
if(empty($v))
{
$error .= "Field " . $k . " is empty\n";
}
}
if(!$error)
{
echo "We don't have any errrors, proceed with code";
}
else
{
echo "Ops we have empty fields.\n";
echo $error;
}
And after you are sure that all the fields are not empty you can do other stuff.

Categories