Albin N
Albin N

Reputation: 1401

How to echo the result array from PDO statement

I have this code:

    $pages = $conn->prepare('SELECT * FROM pages WHERE slug = startpage');

    $pages->execute();

    $resultarray = array();

      while($row = $pages->fetch(PDO::FETCH_ASSOC)){
        $resultarray[] = $row;
      }

I'm trying to do this because I want to use the array in the whole document, not just inside the while. See below example:

    //Somewhere outside of the while loop    
    <h1><?php echo $resultarray['header']?></h1>

What is the most efficient way to do this?

Upvotes: 0

Views: 2597

Answers (3)

som
som

Reputation: 4656

<h1><?php echo $resultarray[$i]['header']?></h1>

Here $i is a index of the $resultarray array.

Upvotes: 0

mychalvlcek
mychalvlcek

Reputation: 4046

dont forget that you have multidimensional array, so for the first row you can access value:

$resultarray[0]['header']

Upvotes: 0

Mihai Stancu
Mihai Stancu

Reputation: 16107

/* instead of the 'while' loop you can use 'fetchAll' */
/* you can use 'while' if the values need to be processed */
$rows = $pages->fetchAll(PDO::FETCH_ASSOC);

/* the final variable will contain all rows */
echo $rows[0]['header'];

Upvotes: 3

Related Questions