Не нравятся результаты поиска? Попробуйте другой поиск!
DLE FAQ » Все вопросы » Общие вопросы по PHP » Почему не выполняется второй запрос в БД в цикле while?

Почему не выполняется второй запрос в БД в цикле while?


     30.03.2017    Общие вопросы по PHP, Модули, MySQL    1223

вопрос
Почему построение комментариев в цикле происходит только 1 раз? Отдельно все строится, если указывать id вручную, но цикл не выполняет больше 1 раза. Если последнюю часть кода убрать с build_comments, то все отрабатывает как надо. Прошу, гуру, подскажите в чем подвох?

require_once ENGINE_DIR . '/classes/mysql.php';
require_once ENGINE_DIR . '/data/dbconfig.php';
require_once ENGINE_DIR . '/modules/functions.php';
require_once ENGINE_DIR . '/modules/sitelogin.php';
require_once ENGINE_DIR . '/classes/templates.class.php';
dle_session();

        $row = 0;
        $output = "";
	$id_annotation = intval($_POST['post_id']); 
		
        $tpl = new dle_template();
        include_once ENGINE_DIR . '/classes/comments.class2.php';
	$comments = new DLE_Comments( $db, $comments_num, intval($config['comm_nummers']) );
		
        $get_annotation = "SELECT * FROM annotation_post where post_id= '$id_annotation'";
        $annotation = $db->query( $get_annotation );

  	if( $config['comm_msort'] == "" OR $config['comm_msort'] == "ASC" ) $comm_msort = "ASC"; else $comm_msort = "DESC";

	if( $config['tree_comments'] ) $comm_msort = "ASC";
	$where_approve = "";
		
       while ( $annotation = $db->get_row() ) 
       {

	$temp = "<div class=\"annotation\">
    <div class=\"annotation-text\">".$annotation['full_story']."
    </div>
    <div class=\"annotation-rating\">
				<div class=\"rate_like-dislike\">
					<div class=\"rate_like-dislike_in\">
						[rating-plus]<span class=\"plus_icon\" title=\"Нравится\"><span>+</span></span>[/rating-plus]
						[rating-minus]<span class=\"plus_icon minus\" title=\"Не нравится\"><span>-</span></span>[/rating-minus]
					</div>
					<span class=\"grey\">{rating}</span>
				</div>
        {comments}
     </div>
    </div>";

$temp = str_replace( '{rating}', ShowCommentsRatingAnnotation( $annotation['id'], $annotation['rating'], $annotation['vote_num'], $user_group[$member_id['user_group']]['allow_rating'] ), $temp);
$temp = str_replace( '[rating-plus]', "<a href=\"#\" onclick=\"doRateAnnotation('plus', '{$annotation['id']}'); return false;\" >", $temp);
$temp = str_replace( '[/rating-plus]', "</a>", $temp);
$temp = str_replace( '[rating-minus]', "<a href=\"#\" onclick=\"doRateAnnotation('minus', '{$annotation['id']}'); return false;\" >", $temp);
$temp = str_replace( '[/rating-minus]', "</a>", $temp);
 
//если удалить ниже, то все работает по циклу
$comments->query = "SELECT annotation_comments.id, annotation_id as post_id, annotation_comments.user_id, date, autor as gast_name, annotation_comments.email as gast_email, text, ip, is_register, annotation_comments.rating, annotation_comments.vote_num, annotation_comments.parent, name, " . USERPREFIX . "_users.email, news_num, comm_num, user_group, lastdate, reg_date, signature, foto, fullname, land, xfields FROM annotation_comments LEFT JOIN " . USERPREFIX . "_users ON annotation_comments.user_id=" . USERPREFIX . "_users.user_id WHERE annotation_comments.annotation_id = '".$annotation['id']."'" . $where_approve . " ORDER BY annotation_comments.id " . $comm_msort;
$comments->build_comments('Default/comments2.tpl', 'news', $allow_full_cache, false );
 $tpl->result['content'] = str_replace ( "<!--dlecomments-->", "\n<div id=\"dle-ajax-comments\"></div>\n", $tpl->result['content'] );
  
       $tpl->result['content'] = str_replace( '{THEME}', "/templates/Default/", $tpl->result['content']);
       $tpl->result['content'] = mb_convert_encoding( $tpl->result['content'], "UTF-8", "windows-1251" ); 
       $temp = str_replace( '{comments}', $tpl->result['content'], $temp);
       
      $output=$output."".$temp;
}
echo $output;

Ответа пока нет


6 комментариев

MikeTheRaven
Юзер

MikeTheRaven - 30 марта 2017 23:05 -

Попробуйте указать идентификатор запроса

$result = $db->query( $get_annotation );
while ( $annotation = $db->get_row($result) ) {
	
}

dmfranklin
Юзер

dmfranklin - 30 марта 2017 23:17 -

К сожалению, это не помогает.

dmfranklin
Юзер

dmfranklin - 31 марта 2017 14:45 -

Ан, нет, сработало, не дождался ответа от сервера, слишком долго страница грузилась в браузере, ибо $tpl->result['content'] не очищался, ваш способ сработал, спасибо!

nowheremany
Эксперт

nowheremany - 31 марта 2017 09:17 -

<?

require_once ENGINE_DIR . '/classes/mysql.php';
require_once ENGINE_DIR . '/data/dbconfig.php';
require_once ENGINE_DIR . '/modules/functions.php';
require_once ENGINE_DIR . '/modules/sitelogin.php';
require_once ENGINE_DIR . '/classes/templates.class.php';
dle_session();

        $row = 0;
        $output = "";
	$id_annotation = intval($_POST['post_id']); 
		
        $tpl = new dle_template();
        include_once ENGINE_DIR . '/classes/comments.class2.php';
	$comments = new DLE_Comments( $db, $comments_num, intval($config['comm_nummers']) );
		
        $annotation = $db->super_query( "SELECT * FROM annotation_post where post_id= '$id_annotation'" );

  	if( $config['comm_msort'] == "" OR $config['comm_msort'] == "ASC" ) $comm_msort = "ASC"; else $comm_msort = "DESC";

	if( $config['tree_comments'] ) $comm_msort = "ASC";
	$where_approve = "";
		
	$temp = "<div class=\"annotation\">
    <div class=\"annotation-text\">".$annotation['full_story']."
    </div>
    <div class=\"annotation-rating\">
				<div class=\"rate_like-dislike\">
					<div class=\"rate_like-dislike_in\">
						[rating-plus]<span class=\"plus_icon\" title=\"Нравится\"><span>+</span></span>[/rating-plus]
						[rating-minus]<span class=\"plus_icon minus\" title=\"Не нравится\"><span>-</span></span>[/rating-minus]
					</div>
					<span class=\"grey\">{rating}</span>
				</div>
        {comments}
     </div>
    </div>";

$temp = str_replace( '{rating}', ShowCommentsRatingAnnotation( $annotation['id'], $annotation['rating'], $annotation['vote_num'], $user_group[$member_id['user_group']]['allow_rating'] ), $temp);
$temp = str_replace( '[rating-plus]', "<a href=\"#\" onclick=\"doRateAnnotation('plus', '{$annotation['id']}'); return false;\" >", $temp);
$temp = str_replace( '[/rating-plus]', "</a>", $temp);
$temp = str_replace( '[rating-minus]', "<a href=\"#\" onclick=\"doRateAnnotation('minus', '{$annotation['id']}'); return false;\" >", $temp);
$temp = str_replace( '[/rating-minus]', "</a>", $temp);
 
//если удалить ниже, то все работает по циклу
$comments->query = "SELECT annotation_comments.id, annotation_id as post_id, annotation_comments.user_id, date, autor as gast_name, annotation_comments.email as gast_email, text, ip, is_register, annotation_comments.rating, annotation_comments.vote_num, annotation_comments.parent, name, " . USERPREFIX . "_users.email, news_num, comm_num, user_group, lastdate, reg_date, signature, foto, fullname, land, xfields FROM annotation_comments LEFT JOIN " . USERPREFIX . "_users ON annotation_comments.user_id=" . USERPREFIX . "_users.user_id WHERE annotation_comments.annotation_id = '".$annotation['id']."'" . $where_approve . " ORDER BY annotation_comments.id " . $comm_msort;
$comments->build_comments('Default/comments2.tpl', 'news', $allow_full_cache, false );
 $tpl->result['content'] = str_replace ( "<!--dlecomments-->", "\n<div id=\"dle-ajax-comments\"></div>\n", $tpl->result['content'] );
  
       $tpl->result['content'] = str_replace( '{THEME}', "/templates/Default/", $tpl->result['content']);
       $tpl->result['content'] = mb_convert_encoding( $tpl->result['content'], "UTF-8", "windows-1251" ); 
       $temp = str_replace( '{comments}', $tpl->result['content'], $temp);
       
      $output=$output."".$temp;

echo $output;

Благодарность принимаю тут Связь

nowheremany
Эксперт

nowheremany - 31 марта 2017 09:25 -

Ответ почему.

Если делать запрос в запросе, то нужно явно указывать откуда забирать данные $handleQueryX

$handleQuery1 = $db->query( .. );
while ( $row = $db->get_row($handleQuery1) ) {

....

$handleQuery2 = $db->query( .. );
while ( $row2 = $db->get_row($handleQuery2) ) {

....

}
$db->free($handleQuery2);

....

}
$db->free($handleQuery1);


Почему такое не делает целсофт - я не знаю. Приходится в некоторых случаях, сначала в массив результаты запроса положить, потом стандартные функции юзать. Двойной перебор получается :(

Благодарность принимаю тут Связь

dmfranklin
Юзер

dmfranklin - 31 марта 2017 14:50 -

Спасибо, ответ почти как и у MikeTheRaven рабочий, вчера так и не дождался ответа от сервера и посчитал его неверным.

Чтобы комментировать - войдите или зарегистрируйтесь на сайте

Похожие вопросы

наверх