简体   繁体   中英

php - Cannot use object of type PDOStatement as array with Google Cloud Messaging

I recently started using PDO to write my applications and i'm currently facing an issue where i'm pulling device ID's from a table and send it over to firebase for push notification purposes. With my below php script when i execute on the page i get this error

Error

Cannot use object of type PDOStatement as array in /Applications/XAMPP/xamppfiles/htdocs/myapp/send_fcm.php

PHP

$row = $conn->query("SELECT device_id,os_type from devices");
while($row->setFetchMode(PDO::FETCH_ASSOC)) {
    $gcmRegIds = array();
    array_push($gcmRegIds, $row['device_id']);
    echo json_encode($gcmRegIds);
}

$url = "https://fcm.googleapis.com/fcm/send";
$token = $gcmRegIds;
$serverKey = 'API_KEY';
$title = "Title";
$body = "Body of the message";
$notification = array('title' =>$title , 'text' => $body, 'sound' =>'default');
$arrayToSend = array('to' => $token, 'notification' =>$notification,'priority'=>'high','badge'=>'1');
$json = json_encode($arrayToSend);

$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: key='. $serverKey;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//Send the request
$response = curl_exec($ch);
//Close request
if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
}
curl_close($ch);

PDO::query returns a PDOStatement object for successful SELECT queries. Let's change the name of that variable, because $row is a bit misleading there.

$stmt = $conn->query("SELECT device_id,os_type from devices");

Now when you fetch from it, you can get rows. setFetchMode() doesn't fetch a row, so we'll just use fetch() with the PDO::FETCH_ASSOC constant defining the fetch mode there.

Assuming you want all the device_id values in an array, you need to move the array initialization ( $gcmRegIds = array(); ) before the loop, or you'll set it back to an empty array before each value is pushed into it and end up with only the last value. Also, the array_push function isn't really necessary to append one item to an array. You can just use [] .

$gcmRegIds = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $gcmRegIds[] = $row['device_id'];
}

And don't json_encode inside the loop, do it afterward, or you'll have repeated, invalid JSON.

echo json_encode($gcmRegIds);

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