2015-10-15 2 views
0

Im пытается вернуть некоторые данные из php в зависимости от времени. т.е. если текущее время больше, чем время публикации, тогда только сообщение должно быть отправлено пользователю, ему следует сообщить, что это запланировано. Проблема в том, что даже если условие выполнено, оно все еще выполняет цикл и дает мне результат «успеха». Любая идея, как преодолеть это?PHP не выходит из цикла

$sql = "Select posts.post_title,posts.author_name,posts.publish_date,posts.post_content,comments.name,comments.comment,comments.time_posted " 
     . "from posts left join comments " 
     . "on posts.id=comments.post_id " 
     . "where posts.id=$data->id " 
     . "LIMIT 5"; 
    $result = mysql_query($sql) or trigger_error(mysql_error() . $sql); 
    $count = mysql_num_rows($result); 
    $index = 0; 
    if ($count >= 1) { 
     $temp = array(); 
     while ($row = mysql_fetch_assoc($result)) { 

      if (strtotime($data->now) > strtotime($row['publish_date'])) { 
       if ($index == 0) { 
        $results[$index]['post_title'] = $row['post_title']; 
        $results[$index]['author_name'] = $row['author_name']; 
        $results[$index]['publish_date'] = $row['publish_date']; 
        $results[$index]['post_content'] = $row['post_content']; 

        $temp[$index]['name'] = $row['name']; 
        $temp[$index]['comment'] = $row['comment']; 
        $temp[$index]['time_posted'] = $row['time_posted']; 
       } else { 
        $temp[$index]['name'] = $row['name']; 
        $temp[$index]['comment'] = $row['comment']; 
        $temp[$index]['time_posted'] = $row['time_posted']; 
       } 
       $index++; 
      } else { 
       $response['status'] = 'Scheduled'; 
       $response['message'] = 'Data present'; 
       break; 
      } 


     } 
     $results[0]['comments'] = $temp; 
     $response['status'] = 'Success'; 
     $response['message'] = 'Data present'; 
     $response['results'] = $results; 

    } else { 
     $response['status'] = '404'; 
     $response['message'] = 'Post does not exist'; 
    } 
    echo json_encode($response); 
+3

Посмотрите на 4 строки сразу после цикла while. Пока ваш запрос возвращает результат, вы всегда сообщаете об успехе! –

ответ

0

так мне удалось решить только с помощью флага переменной

$flag = true; 
    if ($count >= 1) { 
     $temp = array(); 
     while ($row = mysql_fetch_assoc($result)) { 

      if ((strtotime($data->now) > strtotime($row['publish_date'])) == true) { 
       if ($index == 0) { 
        $results[$index]['post_title'] = $row['post_title']; 
        $results[$index]['author_name'] = $row['author_name']; 
        $results[$index]['publish_date'] = $row['publish_date']; 
        $results[$index]['post_content'] = $row['post_content']; 

        $temp[$index]['name'] = $row['name']; 
        $temp[$index]['comment'] = $row['comment']; 
        $temp[$index]['time_posted'] = $row['time_posted']; 
       } else { 

        $temp[$index]['name'] = $row['name']; 
        $temp[$index]['comment'] = $row['comment']; 
        $temp[$index]['time_posted'] = $row['time_posted']; 
       } 
       $index++; 
      } else { 
       $flag = false; 
      } 
     } 
     if ($flag == false) { 
      $response['status'] = 'Scheduled'; 
      $response['message'] = 'Data present'; 
     } else { 
      $results[0]['comments'] = $temp; 
      $response['status'] = 'Success'; 
      $response['message'] = 'Data present'; 
      $response['results'] = $results; 
     } 
0

Не имеет значения, ваше условие выполнено или нет, вы всегда инициализируется статус успеха ($ ответа [ 'статус '] =' Успех ';). Вам нужно переместить эту строку в блок кода, который выполняется при выполнении условия.

Смежные вопросы