简体   繁体   中英

PHP Fetch Associative Array - Selecting Multiple Rows from MySQL DB

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"]);
}
$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"]);
}

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);
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM