ChakshuGautam
10/24/2018 - 5:47 PM

Heroku with Google Cloud SQL and cloud_sql_proxy with PHP / Laravel

Heroku with Google Cloud SQL and cloud_sql_proxy with PHP / Laravel

web: (bash ./start.sh) & vendor/bin/heroku-php-nginx public/

Connecting a mysql to your Cloud SQL instance with the proxy involves the following steps:

{
    "name": "cloudsql-test",
    "type": "project",
    "license": "MIT",
    "authors": [],
    "require": {
        "php": "~7.1.0",
        "ext-gd": "*",
        "ext-mcrypt": "*"
    },
    "scripts": {
        "post-install-cmd": [
            "bash ./proxy.sh"
        ]
    }
}
{
  "type": "service_account",
  "project_id": "your-project",
  …
}
<?php

// public/index.php

$dbname = 'testdb';
$dbuser = 'root';
$dbpass = 'pass?';
$dbhost = '127.0.0.1';
$link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
mysqli_select_db($link, $dbname) or die("Could not open the db '$dbname'");
$test_query = "SHOW TABLES FROM $dbname";
$result = mysqli_query($link, $test_query);
$tblCnt = 0;
while ($tbl = mysqli_fetch_array($result)) {
    $tblCnt++;
  //echo $tbl[0]."<br />\n";
}
if (!$tblCnt) {
    echo "There are no tables<br />\n";
} else {
    echo "There are $tblCnt tables<br />\n";
}
#!/bin/bash
wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.386
mv cloud_sql_proxy.linux.386 cloud_sql_proxy
chmod +x cloud_sql_proxy
// Start the proxy
./cloud_sql_proxy -instances=offmarket-staging:europe-west1:sql-test=tcp:3306 -credential_file=credentials.json