Blue Venrir
Blue Venrir

Reputation: 63

why always keep display "array"

I faced problem on fetching data from database. Why the code always keep display "array"?

$connection_string = $database.':host='.$host_name.';dbname='.$database_name.';charset='.$charset;
$db = new PDO($connection_string, $database_username, $database_password);

$username = $_SESSION['username'];
$password = $_SESSION['password'];
$query = "SELECT password FROM user ";
$st = $db->prepare($query);
$st->execute();
$result = $st->fetchAll(PDO::FETCH_ASSOC);

echo $result; 

Here, I want to take the data from password column. But when i want to check is it fetch or not but it displaying "array". Anyone can help me? Thank you !

Upvotes: 1

Views: 55

Answers (3)

Saqueib
Saqueib

Reputation: 3520

Result returned from db are in associative array PDO::FETCH_ASSOC, echo cannot print elements of array, so its prints array

Use print_r($result) or var_dump($result) to print full array

printr_r($result);

I use a simple function dd() in my development to print debug msg

//Debug Print Functions
function dd($input, $format = 'var_dump') {
   echo ('<pre style="background-color: #FFFBD5;
        border: 1px solid #F8EBAB; padding: 5px;
        margin:5px 0; box-shadow: 2px 2px 0 #F7FFCD">');
   $format($input);
   echo  ('</pre>');
}

Upvotes: 1

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17586

$st = $db->prepare($query);
$st->execute();
$result = $st->fetchAll();

print_r($result);

See the manual fetchAll

An also in your case you are getting only password values , so you can try this way also

$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($result); 

This will print a one dimensional array of passwords

Upvotes: 0

Deval Khandelwal
Deval Khandelwal

Reputation: 3548

You do not refer to each element of the array. You just print the array that will not print the elements of the array. Try this :-

foreach( $result as $r){
  echo $r;
}

or, use print_r($result) (as @Saqueib suggested)

Upvotes: 0

Related Questions