Este tema describe cómo usar PHP para conectarse a un clúster de AnalyticDB for MySQL.
Precauciones
Si usa un sistema operativo Linux, debe instalar php-mysql 5.1.x.
Si usa un sistema operativo Windows, debe instalar php_MySQL.dll.
Para conectarse a un clúster de AnalyticDB for MySQL mediante Internet, agregue la dirección IP del dispositivo from el que se conectará a la lista blanca del clúster de AnalyticDB for MySQL. Para obtener más información, consulte Configure a whitelist.
Conexión a un clúster de AnalyticDB for MySQL con MySQLi
//The endpoint of the 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 cluster. 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 cluster.
$ads_password="account_password";
//The name of the database in the cluster.
$ads_database="db_name";
//The port used to connect to the cluster.
$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)) {
//Obtain data in the user_id column.
echo $row["user_id"];
}
Conexión a un clúster de AnalyticDB for MySQL con PDO
Nota
Para obtener información sobre cómo habilitar PrepareStatement al usar
para conectarse a un clúster de AnalyticDB for MySQL, consulte la sección "PDO" en
Enable PrepareStatement for a client in different programming languages
.
//The endpoint of the 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 cluster. 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 cluster.
$ads_password = "account_password";
//The name of the database in the cluster.
$ads_database = 'db_name';
//The port used to connect to the 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();
}