HTML Registration Form - Array not treated as empty() - php

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 ";
}

Related

if print_r is empty conditional in PHP

I'm trying to get a n else statement working with a print_r such that if there's no value it outputs "no values".
In the code I'm getting values from json converted to an array.
The logic I'm trying to achieve is
IF fieldTag contains "i" THEN output the content associated with it
ELSE says its empty.
Right now blank is outputted as opposed to "no values".
Thanks
for($b=0; $b<count($res['entries'][$i]['bib']['varFields']); $b++) //loop thru the varFields
{
if($res['entries'][$i]['bib']['varFields'][$b]['fieldTag'] == "i")
{
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content']."<br>";
if(count($subfieldText2) > 0) {
print_r($subfieldText2);
} else {
echo "no values";
}
}
}
count() is for arrays, not strings, the way to get the length of a string is with strlen(). And if you want to check for an empty string, just compare it with $var == "", you don't need to get the length.
But you're concatenating "<br>" to the value, so the length will never be zero. You could check the length before concatenating.
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content'];
if($subfieldText2 != "") {
$subfieldText2 .= "<br>";
print_r($subfieldText2);
} else {
echo "no values";
}
And to avoid having to repeat that long expression to access the field, you could use foreach
for($res['entries'][$i]['bib']['varFields'] as $field) {
if ($field['fieldTag'] == "i") {
$subfieldText2 = $field['subfields'][0]['content'];
...
}
}
this worked for me thanks everyone
$subfieldText2="not detected";
echo "ISBN: ";
for($b=0; $b<count($res['entries'][$i]['bib']['varFields']); $b++) //loop thru the varFields
{
if($res['entries'][$i]['bib']['varFields'][$b]['fieldTag'] == "i")
{
$subfieldText2 = $res['entries'][$i]['bib']['varFields'][$b]['subfields'][0]['content'];
echo $subfieldText2.", ";
}
}
echo $subfieldText2;

php check if two variables are empty and merge them togheter

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?
}

GET Multiple MySQL Rows, Form PHP Variables, and Put Into Json Encoded Array

I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}

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.

Function to validate username and password not working [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {

Categories