问题
Ok this might get confusing cos I have not totally worked out how to explain this perfectly but i'll just show code to explain better than i could in words.
Basic idea: I am trying to collect all relevant data from queries assign it to a PHP variable then return it via json.encode for use on the site where ever needs be in Javascript.
So this is an example of what i am trying to do:
$stmt = $pdo->prepare("SELECT * FROM users WHERE uid= ?");
try {
$stmt->execute(array($uid));
} catch (PDOException $e) {
echo $e -> getMessage(); exit;
}
if(!$stmt->rowcount()){
return false; exit;
}
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
So i display $data at this point and i get this result:
Array (
[0] => Array (
[uid] => 1
[pass] => *****
[show_name] => Dave
[email] => test@test.com
) )
This is what i expected to occur :)
Next i want to add more results from queries to "$data". Like so:
$stmt = $pdo->prepare("SELECT * FROM databank WHERE uid=?");
try{
$stmt->execute(array($uid));
} catch (PDOException $e){
echo $e -> getMessage(); exit;
}
$data .= $stmt->fetchAll(PDO::FETCH_ASSOC);
This is where it goes wrong... when i echo/print_r $data at this point the result is:
ArrayArray
Can some one explain why this occurs ? And how i solve it please :)
Thank you for your time!
回答1:
You're concatenating each result to $data as though the results were strings, but they're arrays; when forced to represent an array as a string, PHP produces 'Array', which is not what you want.
Before your first line, do
$data = array();
and in place of your last line, do
$data[] = $stmt->fetchAll(PDO::FETCH_ASSOC)
and you should get
Array (
[0] => Array (
[uid] => 1
[pass] => *****
[show_name] => Dave
[email] => test@test.com
),
[1] => Array (
[uid] => 2
[pass] => *****
[show_name] => Joe
[email] => test@test.com
),
[...]
)
in $data.
Hope this helps!
来源:https://stackoverflow.com/questions/12684417/adding-data-to-php-variable-with-pdo-fetchallfetch-assoc