Reputation: 395
I am trying to put a condition in my form submit. I want to check there no any empty value in my any filed. In my form, I have two textarea and one file upload section.
I have put a condition like below
if (($_POST['question'] != "") AND ($_POST['answer'] != "") AND ($_FILES['picture_name']['name'] != "")) {
echo "ok";
}
else {
echo "field empty";
}
its giving error if file upload or question is empty but its accept and echo ok even answer is empty. Let me know if there anything wrong in my condition. Thanks
Upvotes: 0
Views: 32
Reputation: 3665
I find it best to check for and eliminate all problems before continuing to process code. Hopefully this will get you on the right track as to what may or may not be going as planned.
<?php
$problems = array();
// Check the obvious first.
if (empty($_POST) || empty($_FILES)) {
if (empty($_POST)) {
$problems[] = 'POST empty';
}
if (empty($_FILES)) {
$problems[] = 'FILES empty';
}
}
// If those tests passed, proceed to check other details
else {
// Check if the array keys are set
if (!isset($_POST['question']) || !isset($_POST['answer'])) {
if (!isset($_POST['question'])) {
$problems[] = 'Question not set';
}
if (!isset($_POST['answer'])) {
$problems[] = 'Answer not set';
}
}
else {
// If those tests passed, check if the values are an empty string.
if ($_POST['question'] == "" || $_POST['answer'] == "") {
if ($_POST['question'] == "") {
$problems[] = 'Question empty';
}
if ($_POST['answer'] == "") {
$problems[] = 'Answer empty';
}
}
}
// There are many ways to eliminate problems... The next few lines
// are slightly different since they use elseif conditions (meaning
// only one of them will be displayed, if any).
if (!isset($_FILES['picture_name'])) {
$problems[] = 'Picture name not set';
}
elseif (empty($_FILES['picture_name'])) {
$problems[] = 'Picture name empty';
}
elseif (!isset($_FILES['picture_name']['name'])) {
$problems[] = 'Picture filename not set';
}
elseif (empty($_FILES['picture_name']['name'])) {
$problems[] = 'Picture filename empty';
}
}
// If $problems array is still empty, everything should be OK
if (empty($problems)) {
$outcome = 'OK';
}
// If $problems array has values, glue them together and display
// each one on a new line
else {
$outcome = implode(PHP_EOL, $problems);
}
echo $outcome;
Upvotes: 0
Reputation: 1191
This may help...
if (!empty($_POST['question']) && !empty($_POST['answer']) && is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo "ok";
}
else {
echo "field empty";
}
Upvotes: 1