Google Cloud Platform 開始支援PHP了!
雖然還是在BETA階段, 但還是讓人忍不住要測試一下呀~
這次的測試是使用CodeIgnitor來使用,
結合Google Cloud SQL,
在本機連資料庫MYSQL是沒問題,
但DEPLOY之後發現正式機一直沒辦法連上.
錯誤資訊如下:

A Database Error Occurred
Unable to connect to your database server using the provided settings.
Filename: core/Loader.php
Line Number: 346

查了stackoverflow之後才發現 /application/config/database.php的設定需要微調才能連到資料庫:

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '密碼';
$db['default']['database'] = '資料庫名稱';
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE;
$db['default']['db_debug'] = FALSE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = FALSE;
$db['default']['stricton'] = FALSE;
$db['default']['socket'] = '/cloudsql/PROJECT-ID:INSTANCEID';

最後一行的SOCKET是codeignitor預設沒有的參數,
要記得加上才能成功連線

連線之後, 你會發現網站雖然可以啟動了,
但都沒有資料!怎麼回事呢?
原來是因為他會一直預設連到localhost,
這時必須要修改mysqli的drivers.

到 application/system/database/drivers/mysqli/mysqli_driver.php 將 db_connect 取代成以下的函數:

function db_connect()
{
    if(isset($this->socket)){
        return mysqli_connect(null, $this->username, null, $this->database, null, $this->socket);
    }
    elseif ($this->port != ”)
    {
        return mysqli_connect($this->hostname, $this->username, $this->password, $this->database, $this->port);
    }
    else
    {
        return mysqli_connect($this->hostname, $this->username, $this->password, $this->database);
    }
}

就大功告成拉!

Leave a reply

required

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>