Home >Backend Development >PHP Tutorial >A step-by-step guide to connecting to cloud databases using PHP
PHP applications can connect to cloud databases by following these steps: Create a service account and enable the Cloud SQL API. Create a database instance and set connection credentials. Install the Cloud SQL PHP client library. Use a connection pool to establish a connection to the database. Execute the query and process the results.
Step 1: Create a service account for the database
Transfer Go to the Google Cloud Platform (GCP) console and create a service account. This will grant your PHP application access to the database.
Step 2: Enable Cloud SQL API
In the GCP console, enable Cloud SQL API. This will allow your application to interact with the Cloud SQL service.
Step 3: Create a database instance
In the GCP console, create a Cloud SQL database instance. Select MySQL as the database engine.
Step 4: Set connection credentials
In the Cloud SQL instance details page, create a user and set a password. You need these two credentials to connect to the database in your PHP application.
Step 5: Install the Cloud SQL PHP Client Library
In your PHP application, use the command line to install the Cloud SQL PHP Client Library:
composer require google/cloud-sql-db
Step 6: Connect to the database using a connection pool
Establishing a connection pool is a best practice for efficient interaction with the database. In your app.php
file, add the following code:
// pdo连接 $dsn = sprintf('mysql:dbname=%s;host=%s', $databaseName, $instanceHost); $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => true, PDO::ATTR_EMULATE_PREPARES => false, PDO::MYSQL_ATTR_READ_DEFAULT_FILE => '/etc/my.cnf', ); try { $conn = new PDO($dsn, $username, $password, $options); } catch (PDOException $e) { // 处理错误 }
Step 7: Execute the query
Using PDO:: query()
method executes the query:
$stmt = $conn->query('SELECT * FROM users');
Step 8: Process the results
Use the PDOStatement::fetchAll()
method to process the query Result:
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Practical Case
Consider a simple PHP script that retrieves a list of users from a database:
// 使用连接池获取连接 $conn = get_db_connection(); // 执行查询 $stmt = $conn->query('SELECT * FROM users'); // 处理结果 $users = $stmt->fetchAll(PDO::FETCH_ASSOC); // 输出结果 foreach ($users as $user) { echo $user['name'] . PHP_EOL; }
By following these steps, You can easily use PHP to connect to and interact with cloud databases.
The above is the detailed content of A step-by-step guide to connecting to cloud databases using PHP. For more information, please follow other related articles on the PHP Chinese website!