Jump to content
  • 0

Странный постраничный вывод


Mahay
 Share

Question

Пытаюсь вывести из БД статьи постранично, из 5 статей выводит 10, хотя в базе всего 5 статей.


<?php
require_once("blocks/bd.php");
// Переменная хранит число сообщений выводимых на станице
$num = 10;
// Извлекаем из URL текущую страницу
$page = $_GET['page'];
// Определяем общее число сообщений в базе данных
$result = mysql_query("SELECT COUNT(*) FROM articles");
$posts = mysql_result($result, 0);
// Находим общее число страниц
$total = intval(($posts - 1) / 10) + 1;
// Определяем начало сообщений для текущей страницы
$page = intval($page);
// Если значение $page меньше единицы или отрицательно
// переходим на первую страницу
// А если слишком большое, то переходим на последнюю
if(empty($page) or $page < 0) $page = 1;
if($page > $total) $page = $total;
// Вычисляем начиная к какого номера
// следует выводить сообщения
$start = $page * 10 - 10;
// Выбираем $num сообщений начиная с номера $start
$result = mysql_query("SELECT * FROM articles ORDER BY id DESC LIMIT $start, 10");
// В цикле переносим результаты запроса в массив $postrow
while ( $postrow[] = mysql_fetch_array($result))
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>PERSON ARTS</title>
<link rel="shortcut icon" href="/images/faviconnew.ico" />
<?php include("blocks/code.php"); ?>







<script>
$(document).ready(function(){

// hide #back-top first
$("#back-top").hide();

// fade in #back-top
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#back-top').fadeIn();
} else {
$('#back-top').fadeOut();
}
});

// scroll body to 0px on click
$('#back-top a').click(function () {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});

});
</script>
</head>
<body>
<?php include("blocks/loading.php"); ?>
<div id="band_one">
<div id="head">
<?php include("blocks/head.php"); ?>
</div>
</div>
<div id="band_two">
<div id="reg_panel">
<?php include("blocks/reg_panel.php"); ?>
</div>
</div>
<div>
<div id="rezerv"></div>
</div>
<div>
<div id="page">
<br/>
<table border="0" cellspacing="0" cellpadding="0" width="980px" height="440px" align="center">
<tr>
<td valign="top" align="center" width="10px">

</td>
<td valign="top" align="center" width="720px">




<?php
echo "";
for($i = 0; $i < 10; $i++)
{
echo "
<div style='float: left; margin-left: 15px; margin-bottom: 15px;'>
<a href='photo.php?id=".$postrow[$i]['id']."' id='href_blog'>
<table border='0' cellspacing='0' cellpadding='0' align='center'>
<tr>
<td width='310px' height='190px'>
<div id='conclusion_up'><p style='margin-top: 5px; color: #cfcecb;'><img src='img/photography_1.png' width='20px' align='left' style='margin-right: 5px; margin-left: 10px;'><b>Фото обзор</b> <img src='img/customers.png' align='center' style='margin-right: 5px; margin-left: 130px;'>".$postrow[$i]['view']."</p></div>
<div id='conclusion_data'><p style='margin-top:6px; color: #88c8e0; font-size: 28px;'><b>".$postrow[$i]['day']."</b></p> <p style='margin-top: 10px; margin-left:-2px; font-size: 12px; color: #ebebeb;'><b>".$postrow[$i]['month']."<b></p></div>
<div id='conclusion_shadow'></div>
<img onLoad='init()' src='".$postrow[$i]['face_img']."' width='310px' height='190px'>
<div id='conclusion_down'><br/><p style='margin-left: 10px; margin-top: -12px; color: #cfcecb;'><b>".$postrow[$i]['title']."</b></p></div>
</td>
</tr>
</table>
</a>

</div>
";
}
echo "";
?>
</td>
<td valign="top" align="center" width="250px" style="border-left: 2px solid #e1e1e1;">
<table border="0" cellspacing="0" cellpadding="0" width="250px" align="center">
<tr>
<td id="name_page" height="30px">
<div id="icon"><center><img src="img/photo.png" width="25px" style="margin-top: 3px;"></center></div>
<center><p style="color: #f3f3f3;">Фото обзор<p></center>
</td>
</tr>
<tr>
<td style="background:#73b6d8;" height="20px">
<p style="color: #444444; margin-left: 10px;">Всего статей: <span style="margin-left: 100px;"><b><?php
$q=mysql_query('SELECT COUNT(*) AS `count` FROM `articles`');
$r=mysql_fetch_assoc($q);
echo '('.$r['count'].')';
?></b></span><p>
<div id="navig_pages">
<?php
// Проверяем нужны ли стрелки назад
if ($page != 1) $pervpage = '<a href= ./photos1.php?page=1><<</a>
<a href= ./photos1.php?page='. ($page - 1) .'><</a> ';
// Проверяем нужны ли стрелки вперед
if ($page != $total) $nextpage = ' <a href= ./photos1.php?page='. ($page + 1) .'>></a>
<a href= ./photos1.php?page=' .$total. '>>></a>';

// Находим две ближайшие станицы с обоих краев, если они есть
if($page - 2 > 0) $page2left = ' <a href= ./photos1.php?page='. ($page - 2) .'>'. ($page - 2) .'</a> | ';
if($page - 1 > 0) $page1left = '<a href= ./photos1.php?page='. ($page - 1) .'>'. ($page - 1) .'</a> | ';
if($page + 2 <= $total) $page2right = ' | <a href= ./photos1.php?page='. ($page + 2) .'>'. ($page + 2) .'</a>';
if($page + 1 <= $total) $page1right = ' | <a href= ./photos1.php?page='. ($page + 1) .'>'. ($page + 1) .'</a>';

// Вывод меню
echo $pervpage.$page2left.$page1left.'<b>'.$page.'</b>'.$page1right.$page2right.$nextpage;
?>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<br/><br/>
</div>
<p id="back-top">
<a href="#top"><span></span>Back to Top</a>
</p>
</div>
<div>
<div id="rezerv"></div>
</div>
<div>
<div id="footer">
<?php include("blocks/footer.php"); ?>
</div>
</div>
</body>
</html>

Если исходить из кода, то я выбираю $num = 10;, то есть задаю кол-во выводимых статей на одной стр, при этом все 5 статей выводит, но отображается еще это (см. на картинке) ebe25563072d.jpg

Link to comment
Share on other sites

9 answers to this question

Recommended Posts

  • 0

исходя из того что записей в бд всего 5, а вы поставили в настройках выводить 10 и у вас выводит пять записей, но к ним выводит еще 5 блоков но пустых..., короче говоря - у вас в настройках стоит ограничение на вывод (цифра 10) именно того что в бд, а на вывод блока - нет, то есть html-блок пустой и его выведет, так как стоит цифра 10.

блин! я сам плохо понял что написал, но смысл тот :facepalmxd:

Link to comment
Share on other sites

  • 0

исходя из того что записей в бд всего 5, а вы поставили в настройках выводить 10 и у вас выводит пять записей, но к ним выводит еще 5 блоков но пустых..., короче говоря - у вас в настройках стоит ограничение на вывод (цифра 10) именно того что в бд, а на вывод блока - нет, то есть html-блок пустой и его выведет, так как стоит цифра 10.

блин! я сам плохо понял что написал, но смысл тот :facepalmxd:

а вы не могли бы мне подсказать, что именно нужно исправить в коде?

Link to comment
Share on other sites

  • 0

за вывод картинок этот код отвечает?


<?php
echo "";
for($i = 0; $i < 10; $i++)
{
echo "
<div style='float: left; margin-left: 15px; margin-bottom: 15px;'>
<a href='photo.php?id=".$postrow[$i]['id']
."' id='href_blog'>
<table border='0' cellspacing='0' cellpadding='0' align='center'>
<tr>
<td width='310px' height='190px'>
<div id='conclusion_up'><p style='margin-top: 5px; color: #cfcecb;'><img src='img/photography_1.png' width='20px' align='left' style='margin-right: 5px; margin-left: 10px;'><b>Фото обзор</b> <img src='img/customers.png' align='center' style='margin-right: 5px; margin-left: 130px;'>".$postrow[$i]['view']."
</p></div>
<div id='conclusion_data'><p style='margin-top:6px; color: #88c8e0; font-size: 28px;'><b>".$postrow[$i]['day']
."</b></p> <p style='margin-top: 10px; margin-left:-2px; font-size: 12px; color: #ebebeb;'><b>".$postrow[$i]['month'
]."<b></p></div>
<div id='conclusion_shadow'></div>
<img onLoad='init()' src='".$postrow[$i]['face_img']."
' width='310px' height='190px'>
<div id='conclusion_down'><br/><p style='margin-left: 10px; margin-top: -12px; color: #cfcecb;'><b>".$postrow[$i]['title'
]."</b></p></div>
</td>
</tr>
</table>
</a>

</div>
";
}
echo "";
?>

если да, то видимо как-то так:


<?php
echo "";
for($i = 0; $i < 10; $i++)
{
if(isset($postrow[$i]['face_img']) && !empty($postrow[$i]['face_img'])) { //вот тут добавил условие
echo "
<div style='float: left; margin-left: 15px; margin-bottom: 15px;'>
<a href='photo.php?id=".$postrow[$i]['id']
."' id='href_blog'>
<table border='0' cellspacing='0' cellpadding='0' align='center'>
<tr>
<td width='310px' height='190px'>
<div id='conclusion_up'><p style='margin-top: 5px; color: #cfcecb;'><img src='img/photography_1.png' width='20px' align='left' style='margin-right: 5px; margin-left: 10px;'><b>Фото обзор</b> <img src='img/customers.png' align='center' style='margin-right: 5px; margin-left: 130px;'>".$postrow[$i]['view']."
</p></div>
<div id='conclusion_data'><p style='margin-top:6px; color: #88c8e0; font-size: 28px;'><b>".$postrow[$i]['day']
."</b></p> <p style='margin-top: 10px; margin-left:-2px; font-size: 12px; color: #ebebeb;'><b>".$postrow[$i]['month'
]."<b></p></div>
<div id='conclusion_shadow'></div>
<img onLoad='init()' src='".$postrow[$i]['face_img']."
' width='310px' height='190px'>
<div id='conclusion_down'><br/><p style='margin-left: 10px; margin-top: -12px; color: #cfcecb;'><b>".$postrow[$i]['title'
]."</b></p></div>
</td>
</tr>
</table>
</a>

</div>
";
} // а вот тут закрыл скобочку условия
}
echo "";
?>

Link to comment
Share on other sites

  • 0

а как же не выводить то :) данных 5 а ячеек (TD) 5x2=10

rus, а зачем там условие? Может сразу в FOR заложить точное количество [count(...)]?

человеку нужно вывести именно 10 штук, но вдруг он не успел заполнить табличку в бд на это кол-во?

в итоге выводятся пустые блоки.

я просто в html особо не вглядывался (уж очень большой он), а смысл в том, что если есть элемент массива и он не пустой -> то выводим то что есть, а того что нет - не выводим соответственно ведь проверка идет не только на его существование, но и на пустоту.

Link to comment
Share on other sites

  • 0

Просто не вижу смысла гонять цикл в пустую. Это лишний расход ресурсов.

Тут вообще нужно в запросе к базе просто ставить LIMIT 10, а цикл прогонять по количеству записей. Если их меньше, то и цикл прекратится раньше. Если не чётное количество, то добавить пустую ячейку

вот я как я у себя это сделал. Можно задать любое количество столбцов

$result = '<table><tr>';
// тут задаём сколько столбцов нам надо ($columns - переменная содержит количество столбцов)
$gdn_columns = $columns;
// делаем равную ширину у всех столбцов
$gdn_width = 'width="' . intval(100 / $gdn_columns) . '%"';
// получаем количество записей ($rows - это объект с данными из базы)
$gdn_rows = count($rows);
// прогоняем объект с данными
foreach ($rows as $item) {
$gdn_columns--;
$gdn_rows--;
$result .= '<td ' . $gdn_width . '>';
$result .= $item;
$result .= '</td>';
if ($gdn_columns == 0 AND $gdn_rows > 0) {
$result .= '</tr><tr>';
$gdn_columns = $columns;
}
}
// добиваем недостающие ячейки
if ($gdn_columns != $columns) {
for ($i = 0; $i < $gdn_columns; $i++) {
$result .= '<td></td>';
}
}
$result .= '</tr></table>';

// выводим результат
echo $result;

ps

код выдернул из класса, может где просмотрел ошибку, но работать должен

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy