Need help with if else condition?

if($triptype == 'outstation') {          
    if(isset($_POST['oneway_travel_det1'])) {
        $travelDet = parseValues($_POST['oneway_travel_det1']);
        foreach ($travelDet as $det) {
            if(isset($det['to_airport'])) {
                $toAirport = $det['to_airport'];
            }
            else {
                $toAirport = 0;
            }

            if(isset($det['from_airport'])) {
                $fromAirport = $det['from_airport'];
            }
            else {
                $fromAirport = 0;
            }

            $amt = (!empty($det['est_cost'])) ? $det['est_cost'] : 0;
            $dep_place = $arr_place = '';
            $dep_place = (!empty($det['dep_ocity1'])) ? $det['dep_ocity1'] : $det['dep_oplace1']; //get entered city for international
            $arr_place = (!empty($det['arr_ocity1'])) ? $det['arr_ocity1'] : $det['arr_oplace1']; //get entered city for international

            //insert query
            $query = "INSERT INTO `tools_taxi`.`trip_itenary`(`trip_id`,`departure`,`departure_country`,`arrival`,`arrival_country`,`dept_date`,`dept_time`, `trip_type`) VALUES ('".$taxi_id."','" . $dep_place . "','" . $det['dep_oplace1'] . "','" . $arr_place . "','" . $det['arr_oplace1'] . "','" . date('Y-m-d', strtotime($det['dep_date'])) . "','" . $det['time_zone3'] . "', '".$type_of_trip."')";

            echo "INSERT INTO `tools_taxi`.`trip_itenary`(`trip_id`,`departure`,`departure_country`,`arrival`,`arrival_country`,`dept_date`,`dept_time`, `trip_type`) VALUES ('".$taxi_id."','" . $dep_place . "','" . $det['dep_oplace1'] . "','" . $arr_place . "','" . $det['arr_oplace1'] . "','" . date('Y-m-d', strtotime($det['dep_date'])) . "','" . $det['time_zone3'] . "', '".$type_of_trip."')";

            $res = mysqli_query($taxi_conn, $query);
                if (!$res) {
                    die('bta_travel_itenary table insert failed' . mysqli_error($taxi_conn));  
                    trace_log(__FILE__, __LINE__, $taxi_id . " : " . $query . mysqli_error($taxi_conn));                 
                }
                else{
                    trace_log(__FILE__, __LINE__, $taxi_id . " : History Updated Sucessfully.");
                }
            }
        }
    // }

    else {
        $travelDet = parseValues($_POST['round_travel_det1']);
        foreach ($travelDet as $det) {            
            $amt = (!empty($det['est_cost'])) ? $det['est_cost'] : 0;
            $dep_place = $arr_place = '';
            $dep_place = (!empty($det['dep_rcity1'])) ? $det['dep_rcity1'] : $det['dep_rplace1']; //get entered city for international
            $arr_place = (!empty($det['arr_rcity1'])) ? $det['arr_rcity1'] : $det['arr_rplace1']; //get entered city for international
            //insert query
            $query = "INSERT INTO `tools_taxi`.`trip_itenary`(`trip_id`,`departure`,`departure_country`,`arrival`,`arrival_country`,`dept_date`,`dept_time`, `trip_type`) VALUES ('".$taxi_id."','" . $dep_place . "','" . $det['dep_rplace1'] . "','" . $arr_place . "','" . $det['arr_rplace1'] . "','" . date('Y-m-d', strtotime($det['dep_date'])) . "','" . $det['time_zone3'] . "', '".$type_of_trip."')";

                echo "INSERT INTO `tools_taxi`.`trip_itenary`(`trip_id`,`departure`,`departure_country`,`arrival`,`arrival_country`,`dept_date`,`dept_time`, `trip_type`) VALUES ('".$taxi_id."','" . $dep_place . "','" . $det['dep_rplace1'] . "','" . $arr_place . "','" . $det['arr_rplace1'] . "','" . date('Y-m-d', strtotime($det['dep_date'])) . "','" . $det['time_zone3'] . "', '".$type_of_trip."')";

            $res = mysqli_query($taxi_conn, $query);
                if (!$res) {
                    die('trip_itenary table insert failed' . mysqli_error($taxi_conn));  
                    trace_log(__FILE__, __LINE__, $taxi_id . " : " . $query . mysqli_error($taxi_conn));                 
                }
                else{
                    trace_log(__FILE__, __LINE__, $taxi_id . " : History Updated Sucessfully.");
                }
            }
        }
    }
// 
elseif($triptype == 'city') {
    if (isset($_POST['oneway_travel_det'])) {
        /*One way travel*/
        $travelDet = parseValues($_POST['oneway_travel_det']);
        foreach ($travelDet as $det) {            
            $amt = (!empty($det['est_cost'])) ? $det['est_cost'] : 0;
            $dep_place = $arr_place = '';
            $dep_place = (!empty($det['dep_ocity'])) ? $det['dep_ocity'] : $det['dep_oplace']; //get entered city for international
            $arr_place = (!empty($det['arr_ocity'])) ? $det['arr_ocity'] : null; //get entered city for international
            //insert query
            $query = "INSERT INTO `tools_taxi`.`trip_itenary`(`trip_id`,`departure`,`departure_country`,`arrival`,`dept_date`,`dept_time`, `trip_type`) VALUES ('".$taxi_id."','" . $dep_place . "','" . $det['dep_oplace'] . "','" . $arr_place . "','" . date('Y-m-d', strtotime($det['dep_date'])) . "','" . $_POST['time_zone3'] . "', '".$type_of_trip."')";

            echo "INSERT INTO `tools_taxi`.`trip_itenary`(`trip_id`,`departure`,`departure_country`,`arrival`,`dept_date`,`dept_time`, `trip_type`) VALUES ('".$taxi_id."','" . $dep_place . "','" . $det['dep_oplace'] . "','" . $arr_place . "','" . date('Y-m-d', strtotime($det['dep_date'])) . "','" . $_POST['time_zone3'] . "', '".$type_of_trip."')";

            $res = mysqli_query($taxi_conn, $query);
                if (!$res) {
                    die('bta_travel_itenary table insert failed' . mysqli_error($taxi_conn));  
                    trace_log(__FILE__, __LINE__, $taxi_id . " : " . $query . mysqli_error($taxi_conn));                 
                }
                else {
                    trace_log(__FILE__, __LINE__, $taxi_id . " : History Updated Sucessfully.");
                }
            }
        }
        }
    else {
        if (isset($_POST['round_travel_det'])) {
        /*Round Trip Travel*/
        $travelDet = parseValues($_POST['round_travel_det']);
        foreach ($travelDet as $det) {            
            $amt = (!empty($det['est_cost'])) ? $det['est_cost'] : 0;
            $dep_place = $arr_place = '';
            $dep_place = (!empty($det['dep_rcity'])) ? $det['dep_rcity'] : $det['dep_rplace']; //get entered city for international
            $arr_place = (!empty($det['arr_rcity'])) ? $det['arr_rcity'] : null; //get entered city for international
            //insert query
            $query = "INSERT INTO `tools_taxi`.`trip_itenary`(`trip_id`,`departure`,`departure_country`,`arrival`,`dept_date`,`dept_time`, `trip_type`) VALUES
                            ('".$taxi_id."','" . $dep_place . "','" . $det['dep_rplace'] . "','" . $arr_place . "','" . date('Y-m-d', strtotime($det['dep_date'])) . "','" . $det['time_zone3'] . "', '".$type_of_trip."')";

            echo "INSERT INTO `tools_taxi`.`trip_itenary`(`trip_id`,`departure`,`departure_country`,`arrival`,`dept_date`,`dept_time`, `trip_type`) VALUES
                            ('".$taxi_id."','" . $dep_place . "','" . $det['dep_rplace'] . "','" . $arr_place . "','" . date('Y-m-d', strtotime($det['dep_date'])) . "','" . $det['time_zone3'] . "', '".$type_of_trip."')";

            $res = mysqli_query($taxi_conn, $query);
                if (!$res) {
                    die('trip_itenary table insert failed' . mysqli_error($taxi_conn));  
                    trace_log(__FILE__, __LINE__, $taxi_id . " : " . $query . mysqli_error($taxi_conn));                 
                }
                else{
                    trace_log(__FILE__, __LINE__, $taxi_id . " : History Updated Sucessfully.");
                }
            }
        }
    }

As shown in the above code I am trying to insert the values in the database. The problem here is that when I try to insert values wrt “outstation” condition, only the if condition is executing i.e., $_POST[‘oneway_travel_det1’] and not the $_POST[‘round_travel_det1’]. When I enter data wrt round trip the details are not getting inserted. Please let me know if there is anything wrong.

Your code has 4 choices -

  1. outstation - one way
  2. outstation - round trip
  3. city - one way
  4. city - round trip

I recommend that you indent and add comments to your code so that you can identify the starting and ending point for each of those choices. You currently have an } else { that should be for the city - round trip choice, but it is a point in the logic for a third choice after the outstation and city logic. It is not at the point in the logic for the city - round trip choice.

Part of the problem is you have too much repetitive code. Some suggestions -

  1. If there are only two choices - outstation and city, use an if(…) {…} else {…}. You currently have an if(…) {…} elseif(…) {…} else {…} with the last else {…} being where the mistake is in the logic.
  2. The only thing that should be inside the conditional logic is the code that is different between the choices. You should set up common variables inside the conditional logic, then have only one unique instance of each different INSERT query, that gets executed using the common variables as the input data.
  3. Because the only apparent difference between the two unique INSERT queries is one column, wouldn’t it be easier to set up a common variable in the conditional logic, with a null value for that field, then you could use one single query.
  4. You should use prepared queries, prepared once, before the start of the looping. This will make the queries safe and provide a speed improvement in the execution of the queries. You probably should switch to the much simpler PDO extension, since using prepared queries with the mysqli extension is overly complicated.
  5. While the echo statements for the sql queries are just there for debugging, wouldn’t echo $query; be simpler?
  6. If you use exceptions for handling database statement errors, you can eliminate the error handling logic you have now. Your main code will only ‘see’ error free execution since an error will cause execution to transfer to the exception handling.

In looking at the code further, there are isset() tests for -

$_POST['oneway_travel_det1']
$_POST['oneway_travel_det']
$_POST['round_travel_det']

but there is not one for -

$_POST['round_travel_det1']

The logic assumes that if there is not a ‘oneway_travel_det1’, it must be a ‘round_travel_det1’, but this may not be the case (we don’t know what your submitted data actually looks like.)

This inconstancy may have contributed to the mistake in the } else { logic mentioned above and may have something to do with the incorrect operation you are asking about.

In any case, after you fix the mistakes in the conditional logic, you need to examine what the submitted data actually is (see print_r() or var_dump()) in order to find what’s causing the problem.

I will check with the code and get back to you all. Based on the suggestions i will re-check my code and see.

@phdr Hi. I went through the code and tried changing but unable to insert. The workflow is like:

  1. There are 2 choices namely, Outstation and City Local.
  2. Now when i select Outstation there are further more 2 choices namely round trip and one way. As of now only the one way details are getting inserted for Outstation logic and not the round trip as shown in the above code.
  3. For City local, the logic is same as explained in step 2 but in this for both round trip and one way details are getting inserted properly.
    So can you please help me furthermore?

I need to review the code more, but I am seeing a lot of complication with duplicated code.

To abstract this out, list off what should happen for each combination. What changes?

The following is what your code should end up looking like, with conditional logic only for those things that are different between the choices, and with the other suggestions that have already been made, including using the much simpler PDO extension due to the prepared query -

<?php

// if the 4 values - $_POST['oneway_travel_det1'], $_POST['round_travel_det1'], $_POST['oneway_travel_det'], and $_POST['round_travel_det']
// are being set properly in the form, only one will (should) be set at a time and will uniquely identify which one of the 4 choices to use

// the following reduced code should (untested) work -
if(isset($_POST['oneway_travel_det1']))
{
	// outstation - one way
	$travelDet = parseValues($_POST['oneway_travel_det1']);
	$city = 'ocity1';
	$place = 'oplace1';
	$arr_place = true; // true - use the arr_place for the country. false - use null for the country.
}

if(isset($_POST['round_travel_det1']))
{
	// outstation - round trip
	$travelDet = parseValues($_POST['round_travel_det1']);
	$city = 'rcity1';
	$place = 'rplace1';
	$arr_place = true; // true - use the arr_place for the country. false - use null for the country.
}

if(isset($_POST['oneway_travel_det']))
{
	// city - one way
	$travelDet = parseValues($_POST['oneway_travel_det']);
	$city = 'ocity';
	$place = 'oplace';
	$arr_place = false; // true - use the arr_place for the country. false - use null for the country.
}

// edit - the following line had a typo error in it that has since been corrected
if(isset($_POST['round_travel_det']))
{
	// city - round trip
	$travelDet = parseValues($_POST['round_travel_det']);
	$city = 'rcity';
	$place = 'rplace';
	$arr_place = false; // true - use the arr_place for the country. false - use null for the country.
}

// if the code up to this point can only be executed if there IS a trip, no additional conditional logic is needed
// however, if the code up to this point can get executed without one of these 4 variables being set, one more conditional statement will be needed around the following code

// prepare the query once
$query = "INSERT INTO `tools_taxi`.`trip_itenary`
	(`trip_id`,`departure`,`departure_country`,`arrival`,`arrival_country`,`dept_date`,`dept_time`, `trip_type`)
	VALUES
	(?,?,?,?,?,?,?,?)";
	
// this example uses the much simpler PDO extension and will not work AS IS if all you do is copy/paste it
$stmt = $pdo->prepare($query);

foreach ($travelDet as $det)
{
	// if there's no arrival place (country), use null
	if(!$arr_place){
		$det["arr_$place"] = null;
	}
	
	$dep_place = !empty($det["dep_$city"]) ? $det["dep_$city"] : $det["dep_$place"]; //get entered city for international
	$arr_place = !empty($det["arr_$city"]) ? $det["arr_$city"] : $det["arr_$place"]; //get entered city for international
	$dep_conutry = $det["dep_$place"];
	$arr_country = $det["arr_$place"];

	// execute the query
	$stmt->execute([
		$taxi_id,
		$dep_place,
		$dep_country,
		$arr_place,
		$arr_country,
		date('Y-m-d', strtotime($det['dep_date'])),
		$det['time_zone3'],
		$type_of_trip
	]);

	trace_log(__FILE__, __LINE__, $taxi_id . " : History Updated Successfully.");
}

If one of the choices doesn’t get executed, either in your code or in the above, it is likely because the value being tested isn’t set, and you would need to do something else that has already been suggested and examine the submitted data to find what is causing the problem.

1 Like

Sorry for late reply. I will try it and let you know, thank you so much.

This is the error that I am getting after solving the way you asked me to do.

Hi All,

I tried solving it but facing the issues. No error but the data insertion is not happening for one of the values. So can I make use of swtich statement to solve the bug?

I request you to guide me as I am still not getting any solution for this.

Sponsor our Newsletter | Privacy Policy | Terms of Service