简体   繁体   中英

App Engine (PHP) connection to Cloud SQL failed

I used the environment of the "hello world" app engine example by google to create my own php app. Then i configured the existing app.yaml file to this:

runtime: php55
api_version: 1

handlers:
- url: /
  script: index.php

env_variables:
    MYSQL_DSN: mysql:dbname=sampledb;unix_socket=/cloudsql/sampleproject:europe-west3:sampleinstance
    MYSQL_USER: root
    MYSQL_PASSWORD: admin

My index.php is a typical login page. I want to load user data from my cloud sql to check, whether the user is allowed to enter the next page or not. The next page is a dashboard which includes company data. I also want to load this data from my cloud sql databse.

That's my php code to read the data (i copied it from the google bookshelf tutorial, because i am completly new into these things..)

  <?php
    $dsn = getenv('MYSQL_DSN');
    $user = getenv('MYSQL_USER');
    $password = getenv('MYSQL_PASSWORD');
    if (!isset($dsn; $user) || false=== $password) {
      throw new Exception('Set MYSQL_DSN');
      }
    $db = new PDO($dsn, $user, $password);

    $statement = $db->prepare("SELECT clicks from display_inbox");
    $statement->execute();
    $all = $statement->fetchAll();

    foreach ($all as $data) {
      echo $data["clicks"], "<br>";
    }
  ?>

It's not a specific query,i just want to check the connection. After deploying my app i get the following result:

HTTP-500 error: sampleproject.appspot.com is currently unable to handle this request.

I simply don't get if it's my app.yaml or my php code. Would be very helpful if anybody has an example code for a app.yaml file and a typical query to read the cloud sql data.

You have some syntax errors in your app.yaml and index.php files

Try this:

app.yaml:

runtime: php55
api_version: 1
threadsafe: true

handlers:
- url: /.*
  script: index.php

# [START env]    
env_variables:
    MYSQL_DSN: mysql:unix_socket=/cloudsql/sampleproject:europe-west3:sampleinstance;dbname=sampledb
    MYSQL_USER: root
    MYSQL_PASSWORD: admin
# [END env]

index.php:

  <?php
    $dsn = getenv('MYSQL_DSN');
    $user = getenv('MYSQL_USER');
    $password = getenv('MYSQL_PASSWORD');
    if (!isset($dsn, $user) || false === $password) {
      throw new Exception('Set MYSQL_DSN');
      }
    $db = new PDO($dsn, $user, $password);

    $statement = $db->prepare("SELECT clicks from display_inbox");
    $statement->execute();
    $all = $statement->fetchAll();

    foreach ($all as $data) {
      echo $data["clicks"]."<br>";
    }
  ?>

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