i have tow tables, posts and sections, i want to get the last 10 posts WHERE section = 1,
but use the 10 results in different places, i make a function

            function sectionposts($section_id){
mysql_set_charset('utf8');
$maxpost1 ="SELECT max(id) from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 10";
$maxpost10 =mysql_query($maxpost1);
 return($maxpost10);
    }
$query2 = sectionposts(6);
while ($rows = mysql_fetch_array($query2)){

echo $rows['title'];
echo $rows['id'];
echo $rows['image_section'];
echo $rows['subject'];
echo $rows['image_post'];

how can in take this ten results but use them with different places ,and keep them Arranged from one to ten .
Thanks...

Dani AI

Generated

Short answer: stop doing arithmetic on max(id). When rows are deleted the id sequence is not continuous, so max(id)-N can point to a non‑existent row. Fetch the last N existing rows for the section once, store them in a numerically indexed array, and reuse those array items where you need them on the page.

A compact, modern pattern (using PDO) — fetch once, then reference by index (0 = newest):

function fetchLastPosts(PDO $pdo, $sectionId, $limit = 10){
    $stmt = $pdo->prepare(
      'SELECT * FROM posts WHERE section_id = :sid ORDER BY id DESC LIMIT :lim'
    );
    $stmt->bindValue(':sid', (int)$sectionId, PDO::PARAM_INT);
    $stmt->bindValue(':lim', (int)$limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC); // index 0 = newest
}

$posts = fetchLastPosts($pdo, 6);
// use $posts[0], $posts[1], ... safely (check with isset/count first)

Helper to pull a rank safely:

function postByRank(array $posts, $rank){
    return $posts[$rank] ?? null; // 0-based; returns null when absent
}

Notes and tips:

  • To display oldest→newest among those 10, call array_reverse($posts).
  • If you ever need the “Nth latest” directly in SQL, use LIMIT 1 OFFSET N (but fetching 10 at once is usually cheaper than many single-row queries).
  • Never trust id arithmetic for ordinal positions. Rely on ORDER BY + LIMIT (and OFFSET when needed).
  • Migrate away from the old mysql_* functions to mysqli or PDO and use prepared statements to avoid SQL injection and compatibility problems with newer PHP versions.

was on the right track: fetch once and index the result. This approach just replaces fragile max(id)-N math with a robust, reusable array.

Recommended Answers

All 4 Replies

Member Avatar for Member #120589
function sectionposts($section_id){
    mysql_set_charset('utf8');
    $maxpost =mysql_query("SELECT * from posts WHERE section_id = $section_id ORDER BY ID DESC LIMIT 10");
    if(mysql_num_rows($maxpost)){
        while ($rows = mysql_fetch_array($maxpost, MYSQL_NUM)){
            $output[] = $rows;
        }
    return($output);
    }
}

function formatpost($array, $rank){
    if(isset($array[$rank])){
        $r = $array[$rank];
        $output = "<h3>{$r['title']}</h3>";
        $output .= "<h4>{$r['subject']}</h4>";
        $output .= "<p>{$r['image_post']}</p>";
        $output .= "<img src='{$r['some_image']}' />";
        return $output;
    }
}


$sData = sectionposts(6);

echo formatPost($sData, 0);

...

echo formatPost($sData, 1);

...

echo formatPost($sData, 7);

You could do something like that. NOT TESTED.

Nice answers and it's so helpful, but i didn't make the point well, what am i trying to do is :

1- get ten posts starts from max(id) to "$max(id)-9" form posts table.

2- using the max(id) in the top of the page and then useing $max(id)-1 in a defendant place of the page.

3- i had already generated a code

`Inline Code Example Here

    function getmax_id_with_minus ($minus){
    mysql_set_charset('utf8');
    $maxid ="SELECT max(id) FROM posts";
    $maxid1 =mysql_query($maxid);
        while ($maxid_row = mysql_fetch_array($maxid1)){
                $maxid_id = $maxid_row['0'];
                $maxid_minus = $maxid_id - $minus;
                }
    $selectedpost1 = "SELECT * FROM posts WHERE id = $maxid_minus";
    $query_selectedpost =mysql_query($selectedpost1);
        return ($query_selectedpost);

}
<?php 
$ss = getmax_id_with_minus (8);
while ($rows = mysql_fetch_assoc($ss)){
$main_post_1 = $rows;
?>

`

but i found anouther problem, that, if the client had deleted a post as id = 800 "so there aren't id = 800 in DB" so when i get the max id minus $NUM from it, and this operation must be equal id = 800, so i have a programing mistake here, how can i take care of something like that.

anyway "really" thanks again :) !

Member Avatar for Member #949455

Nice answers and it's so helpful, but i didn't make the point well,

You have to understand that Daniweb is forum where people learn things and share knowledge. What diafol gave is good but you are adding stuff now.

@LastMitch
thanks for makeing this point Mr.LastMitch, i have choosed the forum site to ask and get answers because i have read alot of topics and good topics here, that what pushes me to ask here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.