Check if a field array is empty? - php

I want if value field txtname was empty echo It is ok but it don't work in my code(if field was empty and click on button you see output with print_r(...)), Please see my demo and my code. what do I do?
Demo: http://codepad.viper-7.com/FNWcIs
<form method="post">
<input name="txtname[]">
<button>Click Me</button>
</form>
<?php
if ($_POST) {
$txtname = $_POST['txtname'];
if (!empty($txtname)) {
echo '<pre>';
print_r($txtname); // Output this is: Array ( [0] => )
} else {
echo 'it is ok';
}
}
?>

$txtname or ($_POST['txtname']) is an array with one element. Even that element is empty, empty() returns TRUE for any array that has one or more elements.
That should explain the behavior of your code.
To achieve what you're looking for, change the HTML:
From:
<input name="txtname[]">
To:
<input name="txtname">
If you don't use the brackets, it will be a string. And empty will return FALSE if it is empty. See Variables From External Sources PHP Manual.

change input field name to txtname like show below.
<input name="txtname">
Or if you want to use array of textboxes try below code.
<form method="post">
<input name="txtname[]">
<input name="txtname[]">
<input name="txtname[]">
<button>Click Me</button>
</form>
<?php
if($_POST){
$txtname = $_POST['txtname'];
foreach($txtname as $key=>$value)
{
if(!empty($value)){
echo '<br>'.$value; // Output this is: Array ( [0] => )
}else{
echo '<br>it is ok';
}
}
}
?>

You can try it this way it works if you are not intending to pass one value to the variable $txtname
`
$txtname = $_POST['txtname'];
if($txtname[0]){
echo '<pre>';
print_r($txtname); // Output this is: Array ( [0] => )
}else{
echo 'it is ok';
}
}
?>`

Related

Using isset or is not set with variable in PHP?

I have a form which submits data, and as a test I am attempting to first check if a variable is set on submit. If the variable is set, a text will be displayed stating something like "Variable is set". However if it isn't set, a text will be displayed saying "variable not set", once the variable hasn't been set it should then be set so next time when the form is submitted it displays variable is set however this is not working for me, for some reason it always displays that the variable is not set, my PHP code will be below:
<?php
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
I feel really stupid for not being able to do something which seems so easy, I am only just learning and sort of trying to teach myself, thank you for any help provided!!!
Working code and explanation:
<?php
$test="";
if (isset($_POST["text"])) { //always directly check $_POST,$_GET var without assigning
echo "This var is set";
$test=$_POST["text"]; // then assign
}
else{ // and use else clause for otherwise case
echo "This var is not set";
$test = 'set'; // AND if you want set to default/custom value in case of not set.
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off">
<br /><br />
<input type="submit" value="submit">
</form>
If you are using form to submit values, then try this one,
if (isset($_POST['text'])) {
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
Otherwise, If a variable set to empty value like $test = '';
(It means variable is set but it has no values) It will execute your first if condition only.
<?php
$test=$_GET["text"];
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="#" method="get">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
You haven't declared the variable $test.
Unless you've still got a bit of PHP somewhere that you haven't included here, your variable is empty. When a form is submitted, the input will be added to either the $_POST array (for method = "post") or else the $_GET array (for method = "get").
To Fix:
<?php
if (isset($_POST['text'])) {
$test = $_POST['text'];
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>

Get input from HTML form as an Array and Check if there is input in the array or not

I input values from HTML form as array like this:
<form method = "post" action = "akf.php">
Enter Values in Array $a:<br><br>
<input type="text" name="a[one]" />
<input type="text" name="a[two]" />
<input type="text" name="a[three]" />
<input type="text" name="a[four]" />
<input type="text" name="a[five]" />
<br><br><input type="submit" value="Find"><br><br>
</form>
Now I get those input from PHP from the HTML form and display it like this:
$a=$_POST['a'];
print_r($a);
Now without giving any input in the form (ie., An Empty form) if I submit the form,
It should return the message "No Values entered in the Array ".
Note: I want the PHP to return the above message only after I submit the form.
Functions and Syntax's I used to achieve the output:
if (empty($a))
{
echo 'No Values entered in the Array';
}
else
{
echo 'Array';
}
This doesn't work because: I only returns the message "No Values entered in the Array" when the page is loaded newly, when I click the submit button, PHP takes some value as input and returns the message array.
$sum = array_sum($a);
if($sum==0)
{
echo " No Values entered in the Array ";
}
else
{
echo 'Array';
}
This syntax works only when all the inputs are numerical (numbers of any type) . If I enter strings in array through html forms and SUBMIT, it still prints "No Values entered in the Array"
since array_sum($a); doesn't count strings.
It returns Array because even if you don't enter anything empty strings will be submitted. So if you enter nothing your array will be full of empty strings.
To check if there are only empty strings do:
if(!array_filter($a)) {
echo 'No Values entered in the Array';
}
else {
echo 'Array';
}
array_filter will compare all elements to false and if they are false they will be removed. So if all elements in the array are an empty string the returned array will be empty and therefore validated to false.
See also: Checking if all the array items are empty PHP
you form is:
<form method = "post" action = "akf.php">
Enter Values in Array $a:<br><br>
<input type="text" name="a[]" />
<input type="text" name="a[]" />
<input type="text" name="a[]" />
<input type="text" name="a[]" />
<input type="text" name="a[]" />
<br><br><input type="submit" value="Find"><br><br>
</form>
no need to add any key.
php part:
$values = array_filter($a);
if (!empty($values)) {
echo 'no value';
}else{
echo 'array';
}
In your case you can try something like:
$somethinginarray = false;
foreach($a as $value) {
if(!empty($value)) { // trim this one or put more efficient validation
$somethinginarray = true;
}
}
if($somethinginarray) echo 'Array';
else echo " No Values entered in the Array ";

getting a checkbox array value from POST

i am posting an array of checkboxes. and i cant get it to work. i didnt include the proper syntax in the foreach loop to keep it simple. but it is working. i tested in by trying to do the same thing with a text field instead of a checkbox and it worked with the textfield.
<form method="post">
<?php
foreach{
echo'
<input id="'.$userid.'" value="'.$userid.'" name="invite[]" type="checkbox">
<input type="submit">';
}
?>
</form>
here is the part that is not working. it is echoing 'invite' instead of array.
<?php
if(isset($_POST['invite'])){
$invite = $_POST['invite'];
echo $invite;
}
Your $_POST array contains the invite array, so reading it out as
<?php
if(isset($_POST['invite'])){
$invite = $_POST['invite'];
echo $invite;
}
?>
won't work since it's an array. You have to loop through the array to get all of the values.
<?php
if(isset($_POST['invite'])){
if (is_array($_POST['invite'])) {
foreach($_POST['invite'] as $value){
echo $value;
}
} else {
$value = $_POST['invite'];
echo $value;
}
}
?>
I just used the following code:
<form method="post">
<input id="user1" value="user1" name="invite[]" type="checkbox">
<input id="user2" value="user2" name="invite[]" type="checkbox">
<input type="submit">
</form>
<?php
if(isset($_POST['invite'])){
$invite = $_POST['invite'];
print_r($invite);
}
?>
When I checked both boxes, the output was:
Array ( [0] => user1 [1] => user2 )
I know this doesn't directly answer your question, but it gives you a working example to reference and hopefully helps you solve the problem.
Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.
$invite = implode(', ', $_POST['invite']);
echo $invite;
// if you do the input like this
<input id="'.$userid.'" value="'.$userid.'" name="invite['.$userid.']" type="checkbox">
// you can access the value directly like this:
$invite = $_POST['invite'][$userid];
Because your <form> element is inside the foreach loop, you are generating multiple forms. I assume you want multiple checkboxes in one form.
Try this...
<form method="post">
foreach{
<?php echo'
<input id="'.$userid.'" value="'.$userid.'" name="invite[]" type="checkbox">
<input type="submit">';
?>
}
</form>

Get the name of submit button in PHP

How do I get the name of the submit button in PHP?
I got the value of submit button, but I could not find
any code to get the name of the button. Below is the code I have written.
<form name="form1" method="post">
<input type="submit" value="hello" name="submitbutton">
</form>
<?php
echo "Value of submit button: " . $_POST['submitbutton'];
echo "Name of submit button: " . // What should I do here? //;
?>
You will find the name in the $_POST array.
<?php
print_r($_POST);
?>
This way you will see everything in the $_POST array.
You can iterate through the array with:
foreach($_POST as $name => $content) { // Most people refer to $key => $value
echo "The HTML name: $name <br>";
echo "The content of it: $content <br>";
}
'submitbutton' is the name of your submit button.
you can get the names of super global $_POST array elements with array_keys() function
$postnames = array_keys($_POST);
Its like any other POST variable, the name will be in the $_POST array. The name is the key in the $_POST array.

how to validate a form submit in php

I have a form like this:
<form method="post" action="">
<?php
$h = mysql_query("select distinct sous_sous_categorie, sous_sous_categorie_url
from articles where sous_categorie_url='".$_GET["s_cat"]."' ");
while($hRow=mysql_fetch_assoc($h)){
?>
<span class="submit">
<input type="checkbox" name="<?php echo $hRow["sous_sous_categorie_url"]; ?>"
value="<?php echo $hRow["sous_sous_categorie_url"]; ?>" />
<?php echo $hRow["sous_sous_categorie"]; ?>
</span>
<?php } ?>
<input type="submit" name="submit_sous_sous_categorie_search"
value="search" class="submit" />
</form>
as you can see the form is in a loop, the form consists of checkboxes that user will check and accoding to this a search query will be made, the thing is that checkboxes have the name attribute but this attribute is variable (because it is fetch from the db) so my question is how can I make this:
if(checkboxes are empty){
echo "you must at least select one checkbox"
}
This is just an example but I dont see how to do a simple thing such as
if(!$_POST["checkbox"]}{
echo "you must at least select one checkbox";
}
Again, because the name of the checkboxes are variable.
You can make your checkboxes into an array by changing the name to:
name="checkboxes[<?php echo $hRow["sous_sous_categorie_url"]; ?>]"
Then you can use code like this to make sure at least one is checked:
$passed = false;
if( isset( $_POST['checkboxes'] ) && is_array( $_POST['checkboxes'] ) )
{
foreach( $_POST['checkboxes'] as $k => $v )
{
if( $v )
{
$passed = true;
break;
}
}
}
if( ! $passed )
{
echo "You must select at least one checkbox";
exit();
}
Also, you should be careful with your query there, you need to escape that to prevent SQL injection.
You can pass arrays from your FORM to the PHP script:
<!-- The brackets [] let PHP know you're passing in an array -->
<input type="checkbox" name="categories[]" value="<?php echo $hRow["sous_sous_categorie_url"]; ?>" />
Then in the script:
// $_POST['categories'] is an array when categories are checked.
if (empty($_POST['categories'])) {
echo 'Please select a category.';
} else {
foreach ($_POST['categories'] as $url) {
// do something with $url
}
}

Categories