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

Precautions

  • If you use a Linux operating system, you must install php-mysql 5.1.x.
  • If you use a Windows operating system, you must install php_MySQL.dll.
  • If you want to connect to an AnalyticDB MySQL cluster over the Internet, you must add the IP address of the device from which you want to connect to the AnalyticDB MySQL cluster to the whitelist of the cluster. For more information, see Configure a whitelist.

Use MySQLi to connect to an AnalyticDB MySQL cluster

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

Use PDO to connect to an AnalyticDB MySQL cluster

Note For information about how to enable PrepareStatement if you use PDO to connect to an AnalyticDB for MySQL cluster, see the "PDO" section in Enable PrepareStatement for a client in different programming languages.
//The endpoint of the AnalyticDB MySQL cluster. You can obtain the endpoint on the Cluster Information page in the AnalyticDB for MySQL console.
$ads_server_name = "am-bp***.ads.aliyuncs.com";
//The account used to connect to the AnalyticDB MySQL cluster. AnalyticDB MySQL offers the following types of accounts: privileged accounts and standard accounts.
$ads_username = "account_name"; 
//The password of the account used to connect to the AnalyticDB MySQL cluster.
$ads_password = "account_password"; 
//The name of the database in the AnalyticDB MySQL cluster.
$ads_database = 'db_name'; 
//The port used to connect to the AnalyticDB MySQL cluster.
$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();
}