prepare($query); $statement->execute(); $data = $statement->fetchAll(); foreach ($data as $row) { $output[] = array( 'id' => $row["id"], 'name' => $row["state_name"] ); } echo json_encode($output); } else { $query = " SELECT * FROM district WHERE state_id = '" . $_POST["category_id"] . "' ORDER BY district_name ASC "; $statement = $con->prepare($query); $statement->execute(); $data = $statement->fetchAll(); foreach ($data as $row) { $output[] = array( 'id' => $row["id"], 'name' => $row["district_name"] ); } echo json_encode($output); } }