Log in

View Full Version : how get number of item posted



mostafa_dadgar
01-03-2013, 09:53 AM
hi all
i want write simple code that can replay me number of form item that not empty
for example
i write this code in html page


<form action="getnum.php" method="post">
<input name="test1" type="text" /><br />
<input name="test2" type="text" /><br />
<input name="test3" type="text" /><br />
<input name="test4" type="text" /><br />
<input name="test5" type="text" /><br />
<input name="test6" type="checkbox" value="yes" /><br />
<input name="" type="submit" value="Submit" />
</form>
when this page posted another page i want see how many item is empty or not empty

bernie1227
01-03-2013, 10:28 AM
$a = 0;

if (!empty($_POST['text1'])) {
$a++;
}
if (!empty($_POST['text2'])) {
$a++;
}
if (!empty($_POST['text3'])) {
$a++;
}
if (!empty($_POST['text4'])) {
$a++;
}
if (!empty($_POST['text5'])) {
$a++;
}
if (!empty($_POST['text6'])) {
$a++;
}

echo $a;


Is a simple way to figure out the number of not empty fields. Short of that, you could loop over the entire form to find the not empty fields.

mostafa_dadgar
01-03-2013, 11:04 AM
hi
this way is correct, but if i have 60 item in $_POST i most write Sixty Times of "if (){}" condition
Is there another way?
If I am using a loop in the name must be different in digits
but I have either a different name
for example 'name' 'last name' 'email' ...

Beverleyh
01-03-2013, 11:38 AM
You've just changed your requirements ;)

Bernie's loop suggestion works fine if the name fields were sequentially numbered, like the ones you stated in your opening post. You could increment the number part of "text1", "text2", "text3" too.

To answer the revised query, you could check differently named form fields like this : http://stackoverflow.com/questions/3190464/php-check-if-any-posted-vars-are-empty-form-all-fields-required

Beverleyh
01-03-2013, 11:49 AM
I forgot to include the empty count - something like;

// Required field names
$required = array('login', 'password', 'confirm', 'name', 'phone', 'email');

// Loop over field names, make sure each one exists and is not empty
$error = false;
$a = 0;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
$a++;
}
}

if ($error) {
echo "All fields are required.\n";
echo "$a fields are empty.";
} else {
echo "Proceed...";
}

Untested - on iphone.

VBAssassin
01-06-2013, 11:52 PM
You always use HTML arrays and access the values as an array like this:
http://www.coderprofile.com/site/pastebin/16731