Connect to an AnalyticDB for MySQL cluster using PHP with either the MySQLi extension or PDO (PHP Data Objects).
Prerequisites
Before you begin, ensure that you have:
PHP extension installed:
Linux:
php-mysql 5.1.xWindows:
php_MySQL.dll
The cluster endpoint, database name, username, and password for your AnalyticDB for MySQL cluster. Find these on the Cluster Information page in the AnalyticDB for MySQL console.
If connecting over the Internet: the device IP address added to the cluster whitelist. See Configure a whitelist.
Connect using MySQLi
<?php
// Cluster endpoint — find this on the Cluster Information page in the AnalyticDB for MySQL console.
$ads_server_name = "am-bp***.ads.aliyuncs.com";
// Account name — AnalyticDB for MySQL supports privileged accounts and standard accounts.
$ads_username = "account_name";
$ads_password = "account_password";
// Database name.
$ads_database = "db_name";
// Port.
$ads_port = 3306;
// Connect to the cluster.
$ads_conn = mysqli_connect($ads_server_name, $ads_username, $ads_password, $ads_database, $ads_port);
$strsql = "SELECT user_id FROM my_ads_db.my_first_table LIMIT 20;";
$result = mysqli_query($ads_conn, $strsql);
while ($row = mysqli_fetch_array($result)) {
echo $row["user_id"];
}
?>Connect using PDO
For information about enabling PrepareStatement when using PDO, see the "PDO" section in Enable PrepareStatement for a client in different programming languages.
<?php
// Cluster endpoint — find this on the Cluster Information page in the AnalyticDB for MySQL console.
$ads_server_name = "am-bp***.ads.aliyuncs.com";
// Account name — AnalyticDB for MySQL supports privileged accounts and standard accounts.
$ads_username = "account_name";
$ads_password = "account_password";
// Database name.
$ads_database = "db_name";
// Port.
$ads_port = 3306;
$dsn = "mysql:host={$ads_server_name};dbname={$ads_database};port={$ads_port}";
try {
$dbh = new PDO($dsn, $ads_username, $ads_password);
echo "PDO Success !";
} catch (PDOException $e) {
echo "PDO Connection failed: " . $e->getCode() . "\n" . $e->getMessage() . "\n" . $e->getTraceAsString();
}
?>