0

this is my first question... I am making a dynamic blogging template and I want to show the next 4 blog posts from a MySQL database, here's what I am doing now:

$stmt = $conn->prepare("SELECT id, title, filename, date, content FROM blogs WHERE id=:id");

// bind in execute with an array. 

$values = [
    'id' => $id+1
];

$stmt->execute($values);

while ($row = $stmt->fetch())
{

$filename1 = $row['filename'];
$title1 = $row['title'];
$date1 = date_format(date_create($row['date']),"F j, Y");
$content1 = substr($row['content'], 0, 85);


$photo1 = preg_replace("/\..+/", "-thumb.jpg", $row['filename']);
}

$stmt = $conn->prepare("SELECT id, title, filename, date, content FROM blogs WHERE id=:id");

// bind in execute with an array. 

$values = [
    'id' => $id+2
];

$stmt->execute($values);

while ($row = $stmt->fetch())
{

$filename2 = $row['filename'];
$title2 = $row['title'];
$date2 = date_format(date_create($row['date']),"F j, Y");
$content2 = substr($row['content'], 0, 85);


$photo2 = preg_replace("/\..+/", "-thumb.jpg", $row['filename']);
}

(and the same for 3, 4)

While this for sure works, I feel it is a rather inefficient and expensive way of accomplishing this. What would the correct way of completing this task be?

2
  • 1
    Just pull using BETWEEN $id and $id+4 and loop them Commented Jan 17, 2020 at 22:50
  • 1
    BTW, you don't need a while loop if you're only fetching one row. Commented Jan 17, 2020 at 22:51

1 Answer 1

1

Use ORDER BY and LIMIT to specify how many rows to fetch.

$stmt = $conn->prepare("
    SELECT id, title, filename, date, content 
    FROM blogs 
    WHERE id > :id
    ORDER BY id
    LIMIT 4");
$stmt->execute([':id' => $id]);
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

$posts will then be a 2-dimensional array with all the data for the next 4 posts.

This won't have a problem if the id values aren't sequential, as your code does. That could happen if posts are deleted.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.