1

Currently, I am able to select one row's data from my database table. I was wondering how it would be possible to select information from a specific different row without having to change the code to suit my needs every time. This is for a news article on my website.

Here's my Code:

<?php
session_start();
if(!$_SESSION['username']) {
header('location:index.php');
}
require 'connect.php';
$tbl_name = 'news';
$sql = "SELECT id, title, description, content FROM $tbl_name ORDER BY id DESC LIMIT 3";
$articles = array();
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ('<p class="sidenav">1. <a href="../news.php?article=%o">%s</a></p>',$row["id"],$row["title"]);
?>

Now, as you can see, I've selected 3 rows. How can I output data from more than one row? Currently, this will output nothing if I have more than one row. Is there a way to specifically pinpoint certain information without having to select a row with a specific id?

UPDATE: I've gotten this code now, but what if I wanted to print more than one at a time?

$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
printf ('<p class="sidenav">1. <a href="../news.php?article=%o">%s</a></p>',$row["id"],$row["title"]);
printf ('<p class="sidenav">2. <a href="../news.php?article=%o">%s</a></p>',$row["id"],$row["title"]);
printf ('<p class="sidenav">3. <a href="../news.php?article=%o">%s</a></p>',$row["id"],$row["title"]);
}

2 Answers 2

2
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
    printf ('<p class="sidenav">1. <a href="../news.php?article=%o">%s</a></p>',$row["id"],$row["title"]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

What if I wanted to print more than one at a time? Like I've added in the original post.
0

I was able to accomplish this with the following code.

<?php
$i = 0;
$sql = "SELECT id, title FROM news ORDER BY id DESC LIMIT 3";
if ($stmt = mysqli_prepare($conn, $sql)) {

/* execute statement */
mysqli_stmt_execute($stmt);

/* bind result variables */
mysqli_stmt_bind_result($stmt, $id, $title);

/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
    $i++;
    printf ('<p class="sidenav">' . $i . '. <a href="../news.php?article=%o">%s</a></p>',$id,$title);
}

/* close statement */
mysqli_stmt_close($stmt);
}
?>

2 Comments

And where is the difference to my answer?
@niyou The difference is, yours would only print one of the three results.

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.