This topic describes how to connect to an AnalyticDB for MySQL cluster in PHP.

Precautions

Use MySQLi to connect to AnalyticDB for MySQL

// am-bp***.ads.aliyuncs.com: the endpoint of the AnalyticDB for MySQL cluster to which you want to connect. You can obtain the endpoint on the Cluster Information page of the AnalyticDB for MySQL console.
$ads_server_name="am-bp***.ads.aliyuncs.com"; 
// account_name: the account used to connect to the AnalyticDB for MySQL cluster. There are two types of accounts: privileged and standard.
$ads_username="account_name";
// account_password: the password of the account used to connect to the AnalyticDB for MySQL cluster.
$ads_password="account_password";  
// db_name: the name of the database in the AnalyticDB for MySQL cluster.
$ads_database="db_name"; 
// 3306: the port number of the AnalyticDB for MySQL cluster endpoint.
$ads_port=3306;     
// Connect to the AnalyticDB for MySQL 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)) {
 // user_id: the name of the column to be queried.
  echo $row["user_id"] ; 
}  

Use PDO to connect to AnalyticDB for MySQL

// am-bp***.ads.aliyuncs.com: the endpoint of the AnalyticDB for MySQL cluster to which you want to connect. You can obtain the endpoint on the Cluster Information page of the AnalyticDB for MySQL console.
$ads_server_name = "am-bp***.ads.aliyuncs.com";
// account_name: the account used to connect to the AnalyticDB for MySQL cluster. There are two types of accounts: privileged and standard.
$ads_username = "account_name"; 
// account_password: the password of the account used to connect to the AnalyticDB for MySQL cluster.
$ads_password = "account_password"; 
// db_name: the name of the database in the AnalyticDB for MySQL cluster.
$ads_database = 'db_name'; 
// 3306: the port number of the AnalyticDB for MySQL cluster endpoint.
$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();
}