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

Can I use Google Spreadsheet as a database for my PHP application?

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

我建议你转移到 MySQL 数据库,尤其是 PHP,它们工作得很好,我认为它更可靠 - Google 有一些奇怪的问题可能会很痛苦的服务(例如数据流的上限,这可能会变得非常不方便或昂贵)。此外,如果您的主机是 Apache 上的 运行,MySQL 在那里运行得很好,无需手动设置这些服务。无需外包。

如果您选择 MySQL,您正在研究一个非常简单的(和面向对象编程或过程方法)接口。您可以使用 csv 文件将 Google 电子表格中的当前数据导入 MySQL 数据库。

例如,您的连接如下所示:

糟糕:

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

程序:

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

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

糟糕:

$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 电子表格,请继续阅读,您会发现更多信息。


但是,正如您所说的任何编程语言,我都建议您查看 Python。如果您有任何 Python 熟练程度,或者您愿意学习它,您可以 tutorial from Twilio 作为您想要达到的方向的快速入门。

本教程将引导您了解您需要什么以及如何获得这些依赖项,但快速概述:

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

pip install gspread oauth2client

根据 Twilio,您需要它们:

  1. oauth2client – 使用 OAuth 2.0
  2. 向 Google Drive API 授权
  3. gspread – 与 Google 电子表格交互(如果您认真使用 gspread,请查看 their documentation,它们非常全面)

安装完后,您可以继续从 Google 获取正确的身份验证,您将使用 Google 驱动器 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)