使用PHP,PDO,MYSQL将Android推送通知发送到多个设备

时间:2016-02-07 09:39:34

标签: php android mysql pdo

我已经看过很多使用php和mysql向Android设备发送推送通知的教程但是我想用PDO来实现这个,我一直试图找出问题,我得到了#34;注册无效&# 34;但如果我直接将gcm注册ID分配给变量,但是如果我从数据库获取gcm注册ID,则它正在工作。我认为问题在于从PDO获取数组的结构

这是我得到的错误

{"multicast_id":5263664448936997879,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

当我回复我发送的数组时

    Array ( [registration_ids] => Array ( [0] => Array ( [gcm_id] => APA91bGZs7DIb2lVvtlx-Ltgz2_wbRcMIvy-MfYPxoXt6SyDQlUjEnxgNTEw2vS6U5fe9u62i1LZo_gfhipUqT-FCgDj0U7JAwWwOvVmEhx9xIcs0k6mBsg7AgY6pxCVuaXYhqde0mZd ) ) ) [data] => Array ( [update] => thbtrhrt ) )

我的代码是

function send_notification($registatoin_ids, $message) {

    $url = 'https://android.googleapis.com/gcm/send';
    $fields = array(
        'registration_ids' => $registatoin_ids,
        'data' => $message,
    );
    print_r($fields);
    $headers = array(
        'Authorization: key=AShthdfDeac36l6c6G1huGogerJDUvtvOPQ6hA',
        'Content-Type: application/json'
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

function getGCMIds($univid) 
{
    global $dbConnect;

    $query = $dbConnect->prepare("SELECT gcmid FROM android_gcm_table WHERE univid = ?");
    $query->bindValue(1, $univid);
    $query->execute();

    try
    {
        return $results = $query->fetchAll(PDO::FETCH_ASSOC);
    } 
    catch(PDOException $e)
    {
        die($e->getMessage());
    }
}

$gcmIds = getGCMIds($_POST['univ']); // if i directly paste the gcm reg id here and put $gcmIds in array then its working.
$notification  = $_POST['message'];
$notification = array("update" => $notification);


echo $resultLast = send_notification($gcmIds, $notification);

如果有人帮助我,那就太棒了,谢谢你

1 个答案:

答案 0 :(得分:0)

$ query-> fetchAll(PDO :: FETCH_COLUMN)为我工作

function getGCMIds($univid) 
{
global $dbConnect;

$query = $dbConnect->prepare("SELECT gcmid FROM android_gcm_table WHERE univid = ?");
$query->bindValue(1, $univid);
$query->execute();

try
{
    return $results = $query->fetchAll(PDO::FETCH_COLUMN);
} 
catch(PDOException $e)
{
    die($e->getMessage());
}
}