yura sk
yura sk

Reputation: 41

getting the string array from fetchAll pdo

I am facing something really strange and cant understand why I am getting this next result, I have 2 files, index.php and send.php send.php fetching from the DB list of users and index.php showing the list as table, in index.php I am using require send.php, in send.php i have this code

    $sth->setFetchMode(PDO::FETCH_ASSOC);
    $sth->execute();
    $result = $sth->fetchAll();

    echo '<pre>';
    print_r($result);

and its working great, but in index.php

    <?php if (isset($result)): ?>
        <pre>
            <?php print_($result); ?>
        </pre>
    <?php endif; ?>

I am getting the array like this [0] => array

why?

Upvotes: 0

Views: 918

Answers (1)

Xorifelse
Xorifelse

Reputation: 7911

Should be obvious, unlike fetch() where you iterate over each row fetchAll() returns a list of rows, each being in a separate index of the array.

$result[0]['column'];
        ^
        |-- first result.

So you should do this:

foreach($result as $row){
  echo $row['colname'];
}

This would make $row an array by default, where the key is the column name.


On a side note, if you want to check if you have results do the following:

// this:
if($result){}

// equals:
if(!empty($result)){}

Using isset() will cause unexpected behavior:

if(isset($result = false)){
  // query failed, but this code still executes.
}

Also trying to access a global variable defined in another script is bad practice, avoid doing it. Wrap your code in a small function instead:

function dbGetUsers(){
  // connect to db or whatnot.
  $sth = $pdo->prepare('....');

  if($sth->execute()){
    return $sth->fetchAll();
  } else {
    die('query failed '. __FILE__ . __LINE__ - 2);
  }
}

Upvotes: 1

Related Questions