Dany
Dany

Reputation: 31

using fetch twice in php to get the data

I'm trying to get a data from db, I would to say welcome $row['name']; then in a loop need to print the items

if I did the below code, I will get all items except the first item, but if I deleted the $row2 with the welcoming name, I will get all items why ?

is there a way to use this $row = $SQL->fetch() for both?

<?php
session_start();


include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
    $SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
    $SQL->execute([$_SESSION["userid"]]);
    $row2 = $SQL->fetch();
    echo "Welcome " . $row2['name'] . "<br>";
    while ($row = $SQL->fetch()) {
        echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
    }
}else{
    echo "<h1>Not Logged in. Access denied.</h1>";
}

?>

Upvotes: 0

Views: 413

Answers (1)

miken32
miken32

Reputation: 42695

When you run fetch() you are moving forward the pointer in the result set. So your first call to fetch() gets the first row, second gets the second row, etc.

Probably the easiest approach would be to pull all results into an array and then work with that.

<?php
session_start();


include "connect.php";
$access = isset($_SESSION["userid"]);
if ($access) {
    $SQL = $dbh->prepare("SELECT * from items, users where userid = ?");
    $SQL->execute([$_SESSION["userid"]]);
    $data = $SQL->fetchAll();
    $row2 = $data[0];
    echo "Welcome " . $row2['name'] . "<br>";
    foreach ($data as $row) {
        echo $row["itemname"] . "-" . $row["price"] . "-" . $row["itemqty"] . "<br>";
    }
} else {
    echo "<h1>Not Logged in. Access denied.</h1>";
}

Upvotes: 2

Related Questions