php-awsHow can I use Amazon Web Services to connect to a MySQL database using PHP?
To connect to a MySQL database using PHP and Amazon Web Services (AWS), you will need to use the AWS SDK for PHP. The SDK provides an API for connecting to the database.
The following example code demonstrates how to connect to a MySQL database using the AWS SDK for PHP:
<?php
$rds = new Aws\Rds\RdsClient([
'region' => 'us-east-1',
'version' => 'latest'
]);
$result = $rds->describeDBInstances([
'DBInstanceIdentifier' => 'my-db-instance'
]);
$endpoint = $result['DBInstances'][0]['Endpoint']['Address'];
echo $endpoint;
$link = mysqli_connect($endpoint,"user","password","dbname") or die("Error " . mysqli_error($link));
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * from users";
$res = mysqli_query($link,$query);
if($res === FALSE) {
die(mysqli_error());
}
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
echo "The ID is: " . $row['id'] . " and the Username is: " . $row['username'];
}
mysqli_close($link);
?>
The example code will output the endpoint of the database instance and then use the endpoint to connect to the database. It will then execute a query to retrieve data from the users table.
Code explanation
$rds = new Aws\Rds\RdsClient([
- Initializes a new RdsClient object$result = $rds->describeDBInstances([
- Retrieves information about the database instance$endpoint = $result['DBInstances'][0]['Endpoint']['Address'];
- Stores the endpoint of the database instance$link = mysqli_connect($endpoint,"user","password","dbname") or die("Error " . mysqli_error($link));
- Connects to the database using the endpoint$query = "SELECT * from users";
- Specifies the query to execute$res = mysqli_query($link,$query);
- Executes the querywhile($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
- Iterates over the results of the queryecho "The ID is: " . $row['id'] . " and the Username is: " . $row['username'];
- Outputs the data from the querymysqli_close($link);
- Closes the connection to the database
Helpful links
More of Php Aws
- How can I use PHP to connect to an Amazon Aurora database?
- How do I use PHP to create a ZIP file on AWS?
- How can I use the AWS API Gateway with PHP?
- How can I use AWS and Zksync together with PHP?
- How can I use Yum to install PHP on an Amazon EC2 instance?
- How can I use an AWS SQS Worker with PHP?
- How can I use AWS WAF to secure my PHP application?
- How can I use AWS PHP SDK without credentials?
- How do I generate an AWS Signature Version 4 with PHP?
- How do I determine the version of PHP I am running on AWS?
See more codes...