我可以将Google电子表格用作我的PHP应用程序的数据库吗?

时间:2017-07-24 08:18:32

标签: php google-sheets google-spreadsheet-api

我有数据库Google电子表格。如何使用PHP或任何编程语言处理我的数据库?我是否需要将数据库移动到其他数据库?例如:MySQL

1 个答案:

答案 0 :(得分:0)

我建议你转移到一个MySQL数据库,特别是对于PHP,它们工作得非常好,而且我认为它更可靠 - 谷歌有一些奇怪的怪癖,他们的服务很痛苦(比如限制数据流,这可能变得非常不方便或昂贵)。此外,如果你的主机在Apache上运行,那么MySQL在那里运行得非常好,而无需手动设置这些服务。无需外包。

如果你使用MySQL,那么你正在寻找一个非常简单的(面向对象的编程或程序方法)接口。您只需使用csv文件将Google电子表格中的当前数据导入MySQL数据库。

例如,您的连接看起来像:

OOP:

$_connection = new mysqli(host, user, password, database);

程序:

$_connection = mysqli_connect(host, user, password, database);

然后,您可以使用简单查询从数据库中SELECT值:

OOP:

$sql = "SELECT row1, row2, row3 FROM table";

if ($result = $_connection->query( $sql ))
{
    if ($result->num_rows > 0)
    {
        while ($row = $result->fetch_assoc())
        {
            //... get using the associate method
            echo $row['row1'];
            // etc...
        }
    }
}

程序:

$sql = "SELECT row1, row2, row3 FROM table";
$result = mysqli_query($_connection, $sql);
$row = mysqli_fetch_assoc($result);
echo $row['row1'];

所以我的建议确实是你开始使用MySQL。这很简单,有很多关于它的文档。

如果您有兴趣,可以从here找到官方的PHP文档。

如果您仍想使用Google Spreadsheets,请继续阅读,您会发现更多内容。

但是,正如您所说的任何编程语言,我建议您查看Python。如果你有任何Python熟练程度,或者你愿意学习它,那么你可以tutorial from Twilio作为你试图获得的方向的跳跃式开始。

本教程将引导您完成所需内容以及如何获取这些依赖项,但需要快速概述:

您需要gspread以及Google的API oauth2client。这是一个简单的命令 - 假设你有pip

pip install gspread oauth2client

根据Twilio你需要它们:

  1. oauth2client - 使用OAuth 2.0使用Google Drive API进行授权
  2. gspread - 与Google Spreadsheets互动(如果您认真使用gspread,请查看their documentation,它们一直很漂亮)
  3. 安装完毕后,您可以继续从Google获得正确的身份验证,您将使用Google Drive API。 Twilio向您展示了如何做到这一切。

    假设您拥有正确的依赖关系,并且已使用Google Drive API授权您的应用,那么您就可以开始使用代码:

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    
    
    # use creds to create a client to interact with the Google Drive API
    scope = ['https://spreadsheets.google.com/feeds']
    creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)
    client = gspread.authorize(creds)
    
    # Find a workbook by name and open the first sheet
    # Make sure you use the right name here.
    sheet = client.open("Copy of Legislators 2017").sheet1
    
    # Extract and print all of the values
    list_of_hashes = sheet.get_all_records()
    print(list_of_hashes)
    
相关问题