简体   繁体   中英

PHP PDO fetch and foreach - I'm not getting the first column

This is my first post, so I'm just getting to know how the community works so I can be helpful too, later on...

I have an index.php and db.php for testing PDO in a very small and simple app, in the first one goes the html and the second the database connection.

index.php

 <h1><?php echo $fjoin_bookname; ?></h1>
    <?php foreach($join as $j): ?>
        <tr>
            <td> 
                <?php echo 'Page: '. $j['pageNumber']; ?>
            </td>
            <td>
                <?php echo $j['pageNote']; ?>
            </td>
        </tr>
    <?php endforeach; ?>

db.php

//get books and pages Join
    $query='SELECT * 
            FROM books
                INNER JOIN pages
                ON books.bookID = pages.bookID
            ORDER BY pageNumber ASC';

    $join = $db->query($query);
    $fjoin = $join->fetch();
    $fjoin_bookname = $fjoin['bookName'];

It is an app that gets page numbers with a corresponding note from a book, this will help to keep track of several books while on different devices.

Problem: I'm not getting the first row from the 'pages' table. It was working fine until I inserted the fetch method

$fjoin = $join->fetch();
$fjoin_bookname = $fjoin['bookName'];

Question Would anyone be so kind to help me work this out?

When you do a call of

$join->fetch()

it returns item from current position and move cursor to the next one. You can fetch all elements to a var and then get fjoin_bookname from the first element:

db.php

//get books and pages Join
$query='SELECT * 
        FROM books
            INNER JOIN pages
            ON books.bookID = pages.bookID
        ORDER BY pageNumber ASC';

$statement = $db->query($query);
$join = $statement->fetchAll();
$fjoin = $join[0];
$fjoin_bookname = $fjoin['bookName'];

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