Error occurs when no checkbox is checked (in PHP) - php

I have a php code where data from my database are fetched in an array with checkbox corresponding each data . I already have the codes enabling updates to my table (for each data checked):
<?php
include("connect.php");
$user=$_SESSION['username'];
$updated = FALSE;
$submit=FALSE;
if(count($_POST) > 0){
$library = $_POST['library'];
array_map('intval',$library);
$library = implode(',',$library);
mysql_query("UPDATE ES_Students SET library=0") or trigger_error(mysql_error
(),E_USER_ERROR);
mysql_query("UPDATE ES_Students SET library=1 WHERE StudentNO IN ($library)") or trigger_error
(mysql_error(),E_USER_ERROR);
$submit=TRUE;
$updated=TRUE;
}
?>
My problem is, whenever no checkbox is checked, an error will occur that the library index is undefined and all. I know it's got something to do with the $count($_POST)>0 but I don't actually know how to fix this. I tried putting an else-clause to redirect it to another page but it will result to same error. Can anyone tell me what to do??

Use an isset around your post. PHP link
if( isset($_POST) && count($_POST) > 0){
....
If any data is sent at all, even a blank form, isset($_POST) will return true, but with a count($_POST) of 0. So, you could also test for the exact items of the array you're looking for to be sure it is infact in the $_POST :
if( isset($_POST) && count($_POST) > 0 && isset($_POST['library'])){
....

you should check if $_POST['library'] contains any items, because if it's empty, then the implode function returns an empty string and your query looks like ... IN () which is not valid sql syntax.

Related

isset or !empty to determine if Wordpress array has content?

I'm using the ACF Gallery plugin for Wordpress that produces an array of image data.
It's called as so:
$floorplans = get_field('floorplans');
My problem is that sometimes, the array doesn't have any proper content e.g if i var_dump() it and they haven't uploaded any content, I get:
string(0) ""
If the result stored in $floorplans is empty, I want the script to skip over some statements.
I've tried:
if(!empty(get_field('floorplans'))){
...
}
... and yet the statements in my if still occur.
I tried:
if(isset(get_field('floorplans'))){
...
}
And I get:
Fatal error: Cannot use isset() on the result of a function call
So then I tried:
$floorplanCount = count(get_field('floorplans'));
if ($floorplanCount !== 0){
...
}
And you guessed it, the statements in the if still pass.
So how can I not run a section of code if there is nothing in my floorplans field?
As mentioned in comments get_field is the culprit, and a shining example of why a function shouldn't return multiple data types (array or string, array or int, etc), because it forces complexity on the calling code to have to figure out what was returned.
Try this:
if (((true === is_array($floorplans)) && (count($floorplans) > 0)) || (false === empty($floorplans))) {
// Do work
}
According to acf gallery documentation, you can use
if($floorplans)
{
//your statements goes here
}
Here is the link. http://www.advancedcustomfields.com/resources/gallery/
The reason why you cant use isset is, the get_field function returns the array if anything exists, else it will return a false or 0 ( Im not sure, but even if it is 0 or false the $floorplan variable should work seamlessly in the if statement as I mentioned above )
Here is more documentation just in case : http://www.advancedcustomfields.com/resources/get_field/

Differentiate between blank form and 0 using php for html5 form handling

if(isset($_POST['n']) ){
$n = $_POST['n'];
if(!empty($n) || $n==0){
echo "n is any number including 0 but not blank";
}
}
How do I check if the form values are blank but can be 0 ? isset($_POST['$var']) is returning true even if the html form is blank. I tried doing the above code but it still isnt working. I can't seem to find a way to separate a blank form and 0.
Text inputs are considered successfull even if they are empty so don't use isset(). An empty string and 0 are both empty() so don't use it here. Try checking for an empty string:
($_POST['n'] != '')
Or since you are expecting numbers look at is_numeric() or ctype_digit().

PHP - proper check if $_POST['variable'] is posted

I want to check if $_POST['submit'] is posted.
My original code was:
if ($_POST['submit']) { }
But I have a PHP notice with this code - "Undefined index: submit in..."
So to remove the notice I have to write this:
if (isset($_POST['submit'])) { }
But this is pointless because $_POST array is global and it return always true.
Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:
if (isset($_POST['submit']) && $_POST['submit'] != 0) { }
In this particular case I prefer:
if ($_POST['submit']) {}
But here I get the PHP notice.
So which way is the most proper/accepted?
Thank you
isset($_POST['submit']) checks if the submit key is set in the $_POST array. It doesn't just check whether the $_POST array exists and is therefore not "pointless". If you want to check whether the value is not falsey (== false), which includes 0, without triggering an error, that's what empty is for:
if (!empty($_POST['submit']))
which is the same thing as
if ($_POST['submit'])
but without triggering a notice should the value not exist.
See The Definitive Guide To PHP's isset And empty for an exhaustive explanation.
Try
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//do
}
As of PHP version 7 there is a new method available called "Null Coalesce Operator". This method saves you time and space in your code.
$submit = $_POST['submit'] ?? '';
If submit key does not exist or is NULL the value of the $submit variable will be an empty string.
This method is not limited to $_POST. It will work for any variable. For example:
echo $my_message ?? 'No message found';
If message was not initialized or is NULL, the statement above will output No message found
There's even more that you can do with a null coalesce operator, documentation link below.
Documentation here
$_POST[] checks to see if a variable is submitted and not the form name.
if ( isset($_POST['name']) ) {
// work here
}
As per my understanding, It should be like below:
if (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){
# if method is post, code goes here.
}
and if you are sure that your method is POST for sure. and you have data post in $_POST you can use code like below:
if (isset($_POST['submit']) && $_POST['submit'] != '') {# I think, '' instead of 0
# if data is posted, code goes here.
}
I usually prefer $_POST.

PHP isset not working properly on form, with loops and arrays

This is honestly the most finicky and inept language I've ever coded in. I'll be glad when this project is good and over with.
In any case I have to us PHP so here's my question.
I have an Array named $form_data as such:
$form_data = array
('trav_emer_med_insur',
'trav_emer_single',
'trav_emer_single_date_go',
'trav_emer_single_date_ba',
'trav_emer_annual',
'trav_emer_annual_date_go',
'trav_emer_extend',
'trav_emer_extend_date_go',
'trav_emer_extend_date_ef',
'trav_emer_extend_date_ba',
'allinc_insur',
'allinc_insur_opt1',
'allinc_single_date_go',
'allinc_single_date_ba',
'allinc_insur_opt2',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'cancel_insur',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'visitor_insur',
'country_select',
'visitor_supervisa',
'visitor_supervisa_date_go',
'visitor_supervisa_date_ba',
'visitor_student',
'visitor_student_date_go',
'visitor_student_date_ba',
'visitor_xpat',
'visitor_xpat_date_go',
'visitor_xpat_date_ba',
'txtApp1Name',
'txtApp2Name',
'txtApp1DOB',
'txtApp2DOB',
'txtApp1Add',
'txtApp1City',
'selprov',
'txtApp1Postal',
'txtApp1Phone',
'txtApp1Ext',
'txtApp1Email',
'conpref', );
These are the names of name="" fields on an HTML form. I have verified that ALL names exist and have a default value of '' using var_dump($_POST).
What I want to do is very simple, using the $form_data as reference do this:
create a new array called $out_data which can handle the data to display on a regurgitated form.
The structure of $out_data is simple the key will be the name of the element from the other array $out_data[txtApp1Name] for example, and then the value of that key will be the value.
Now what I want is to first check to see if every name="" is set or not, to eliminate errors and verify the data. Then regardless of whether it is set or not, create its placeholder in the $out_data array.
So if $_POST[$form_data[1]] (name is 'trav_emer_single') is not set create an entry in $out_data that looks like this $out_data([trav_emer_single] => "NO DATA")
If $_POST[$form_data[1]] (name is 'trav_emer_single') is set create and entry in $out_data that looks like this: $out_data([trav_emer_single] => "whatever the user typed in")
I have tried this code:
$out_data = array();
$count = count($form_data);
for( $i = 0; $i < $count; $i++ )
{
if(!isset($_POST[$form_data[$i]])) {
$out_data[$form_data[$i]] = "NO_DATA";
}
else {
$out_data[$form_data[$i]] = $_POST[$form_data[$i]];
}
}
Now this code technically is working, it is going through the array and assigning values, but it is not doing so properly.
I have hit submit on the form with NOTHING entered. Therefore every item should say "NO_DATA" on my regurgitated output (for user review), however only some items are saying it. All items I have confirmed have name="" and match the array, and have nothing entered in them. Why is "NO_DATA" not being assigned to every item in the array?
Also of note, if I fill in the form completely $out_data is fully and correctly populated. What is the problem with !isset? I've tried doing $_POST[$form_data[$i]] == '' which does put no_data in every instance of no data, however it throws an 'undefined index' warning for every single item on the page whether I write something in the box or not.
Really I just want to know WTF is going on, the dead line for this project is closing fast and EVERY step of the PHP gives me grief.
As far as I can tell by reading around my code is valid, but refuses to execute as advertised.
If you need more code samples please ask.
Really befuddled here, nothing works without an error, help please.
Thanks
-Sean
Instead of checking !isset(), use empty(). If the form posts an empty string, it will still show up in the $_POST as an empty string, and isset() would return TRUE.
I've replaced your incremental for loop with a foreach loop, which is almost always used in PHP for iterating an array.
$out_data = array();
foreach ($form_data as $key) {
if(empty($_POST[$key])) {
$out_data[$key] = "NO_DATA";
}
else {
$out_data[$key] = $_POST[$key];
}
}
PHP's isset returns TRUE unless the variable is undefined or it is NULL. The empty string "" does not cause it to return FALSE. empty() will do exactly what you need, though.
http://php.net/manual/en/function.isset.php
isset() will return FALSE if testing a variable that has been set to
NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP
NULL constant.
Returns TRUE if var exists and has value other than NULL, FALSE
otherwise.

I need to check if multiple items are set and not empty in PHP

Below is a snippet of PHP that I need to get working, I need to make sure that 3 items are not set already and not === ''
I have the part to make it check if not set but when I try to see if the values are empty as well (I might not even be thinking clearly right now, I might not need to do all this) But I need to make sure that redirect, login_name, and password are all not already set to a value, if they are set to a value I need to make sure that the value is not empty.
Can someone help, when I add in check to see if values are empty, I get errors with my syntax, also not sure if I should have 5-6 checks like this in 1 if/else block like that, please help
I need to check the following:
- $_GET['redirect'] is not set
- $_REQUEST['login_name'] is not set
- $_REQUEST['login_name'] is not != to ''
- $_REQUEST['password'] is not set
- $_REQUEST['password'] is not != to ''
if (!isset($_GET['redirect']) && (!isset($_REQUEST['login_name'])) && (!isset($_REQUEST['password']))){
//do stuff
}
UPDATE
Sorry It is not very clear, I was a bit confused about this. Based on Hobodaves answer, I was able to modify it and get it working how I need it. Below is the code how I need it, it works great like this... So if that can be improved then that is the functionality that I need, I just tested this.
if (!isset($_GET['redirect'])
&& empty($_GET['redirect'])
&& isset($_REQUEST['login_name'])
&& !empty($_REQUEST['login_name'])
&& isset($_REQUEST['password'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
if this was loaded then it will run the login process
login.php?login_name=test&password=testing
If this is loaded then it will NOT run the login process
login.php?login_name=test&password=
if (!isset($_GET['redirect'])
&& !isset($_REQUEST['login_name'])
&& empty($_REQUEST['login_name'])
&& !isset($_REQUEST['password'])
&& empty($_REQUEST['password'])
) {
// do stuff
}
This is exactly what you describe, (not != empty === empty). I think you should edit your question though to explain what you're triyng to do, so we can suggest better alternatives.
Edit:
Your updated question can be simplified as:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
} {
// load user
}
A more maintainable solution would be storing each key in an array, and then foreach over it and check if isset or empty. You're not very DRY with your current solution.
The implementation would look someting like:
<?php
$keys = array('login_name', 'password');
foreach($keys as $key)
{
if(!isset($_REQUEST[$key]) || empty($_REQUEST['key'])
// Show error message, kill script etc.
}
// Dot stuff
?>
If a global variable is not set, that is the same as being empty. Thus:
!is_set(($_REQUEST['username'])) is the same as empty($_REQUEST['username'])
So based on your update, you can simplify to:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
please read!
Sorry, the previous answer I gave will not give you what you want. Here is why:
If you use !_REQUEST['password'], it will return true if the password is empty or if it is not set. However if you use if($_REQUEST['password']) it will pass the conditional anytime that global variable is set, even if it is empty.
Therefore I recommend:
$no_redirect = (!$_GET['redirect']);
$login_name = (!$_REQUEST['login_name']) ? false : true;
$password = (!$_REQUEST['login_name']) ? false : true;
if($no_redirect && $login_name && $password) {
echo 'load user';
}
Sorry for the previously bad info.
You could create an array
$array = array(
$_GET['redirect'],
$_GET['redirect'],
$_REQUEST['login_name'],
$_REQUEST['login_name'],
$_REQUEST['password'],
$_REQUEST['password']
);
foreach($array as $stuf)
{
if(!empty($stuff) && $tuff !=0)
//do something
}

Categories