简体   繁体   中英

PHP 500 internal server error when calling a php function

I have a problem lately I have created a function in my php file, and I am trying to call the function from the same file but when I call it i just get 500 internal server error.

function messageThem($match, $message) {


if(isset($match) & isset($message)) {
$query = "SELECT gcm FROM gcm_users";
$result = $con->query($query, MYSQLI_USE_RESULT);

$regID = array();
while($r = mysqli_fetch_array($result)) {
$regID[] = $r["gcm"];
}



$url = "https://gcm-http.googleapis.com/gcm/send";
$api = "REMOVED. API KEY MAY NOT BE SHARED";
$data = array('match' => $_POST['match'], 'message' => $_POST['message']);
$fields = array('registration_ids' => $regID,'data' => $data);
$headers = array('Authorization: key=' . $api,
             'Content-Type: application/json');



printf("np bro");

//curl connection
$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));

$resultCurl = curl_exec($ch);

  if ( curl_errno( $ch ))
{
    echo 'GCM error: ' . curl_error( $ch );
}

curl_close($ch);

echo $resultCurl;


}


}
messageThem("1200","message goes here");

The only thing I achieve from this is an internal server error. But then if I remove the function and just run the code it works perfect. So it likes when I want to call it it gives me and internal server error.

Error is raised because $con variable is not defined and You call query method on it - definitely a scope problem. Probably You got error: Fatal error: Call to a member function query() on a non-object

So there are two solutions:

  1. You have to use

global $con;

  1. or You have to pass $con as third argument to the function.

I assume, that $con is an object of db connection here.

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