If condition check not working and execute even when the condition is false while doing post operation

nish darsh
nish darsh used Ask the Experts™
Hello experts,

I am trying to check if the post data obtained for 'fields' is empty. I have tried different conditions to check if the array is empty or not. Even if the 'fields' is empty, the if condition executes. It would be great if someone could suggest me as to how to go about with this.

<h4>Alternatives</h4><input type="text" style="width:700px;display: inline" id="fields" name="fields[]" placeholder="Enter Method Name" class="form-control method_list_list"/> <input type="button" name="addmore" id="addmore" class="btn btn-success" value="Add More"/>

public function addmethodtotask(){
	 $conn= mysqli_connect("localhost","root","","cognitivewalkthrough");
	 $taskid=  $_POST['taskid'];
	$description =  $_POST['reason'];
	$action = $_POST['action'];

//if (isset($_POST['fields']) && $_POST['fields'] != "") {
	if (isset($_POST['fields']) && $_POST['fields'] != NULL) {
	// if (count($_POST['fields'])>0 && !empty($_POST['fields'])) {
		 echo "whey am i here";
				foreach ( $_POST['fields'] as $key=>$value ) {
					$sql_website = sprintf("INSERT INTO method (methodname,description,action) VALUES ('%s','%s','%s')",mysqli_real_escape_string($conn,$value),mysqli_real_escape_string($conn,$description),mysqli_real_escape_string($conn,$action) );
					$inserted_method_id = $this->db->insert_id();
	$this->db->join('task_method', 'method.methodid = task_method.methodid');
	$this->db->join('task', 'task.taskid = task_method.taskid');
	$records = $this->db->get('');
	return $records->result();

Open in new window

Thanks in advance.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Your POST array will contain the fields key, even if the text boxes are empty. It will only NOT contain that key if they don't exist at all in the form. What you need to do is loop through the fields array and check the value for each one to determine whether it's empty:

if (isset($_POST['fields'])):
    // we have at least one field entry
    foreach ($_POST['fields'] as $field):
        if ($field != ""):
            // this field has a value so do something with it :)

Open in new window

nish darshStudent


Thank you.. was looking for this solution..

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial