使用PHP连接Azure Database for MySQL时遇到连接问题
Hey there, let's work through your connection problem step by step. I've reviewed your PHP code and there are several common pitfalls with Azure MySQL + XAMPP that we can fix right away:
Common Fixes & Checks
1. Verify Azure Firewall Rules
Azure Database for MySQL blocks all external connections by default. You need to add your XAMPP machine's public IP address to the server's firewall allowlist in the Azure Portal:
- Go to your Azure MySQL server resource
- Navigate to Connectivity > Firewall rules
- Add a new rule with your local machine's public IP (you can look it up via
curl ifconfig.meor a quick search) - For testing, you can temporarily set the start IP to
0.0.0.0and end IP to255.255.255.255(don't leave this enabled long-term for security)
2. Force SSL Connection (Required by Azure)
Azure MySQL mandates SSL connections, but your current code doesn't include SSL parameters. Here's how to add them:
- First, ensure you have the correct CA certificate. XAMPP usually includes one at
C:/xampp/php/extras/ssl/cacert.pem(Windows) or/opt/lampp/php/extras/ssl/cacert.pem(Linux/macOS). If not, save the official Azure CA cert to that path. - Update your mysqli connection to include SSL settings.
3. Fix Parameter Syntax (If Using Older PHP Versions)
Your code uses named parameters (host: '...') which only work in PHP 8.0+. If your XAMPP's PHP version is older than 8.0, this will throw an error. Switch to positional parameters instead.
4. Output Detailed Error Messages
Instead of a generic "Could not connect" message, print the specific error code and message—this will help pinpoint the exact issue.
Modified Working Code Example
class access { var $user = "your_username@autosign"; // Azure requires username@servername format var $pass = "your_password"; var $conn = null; var $result = null; var $StudentID = null; var $sql = null; public function connect() { // Positional parameters (works for all PHP versions >=5.6) $this->conn = mysqli_connect( 'autosign.database.windows.net', $this->user, $this->pass, 'Automat', 3306, // Azure MySQL default port, explicitly specify it null, [ 'ssl_mode' => MYSQLI_CLIENT_SSL, 'ssl_ca' => 'C:/xampp/php/extras/ssl/cacert.pem' // Adjust path to match your XAMPP setup ] ); if (!$this->conn) { // Print detailed error info echo 'Connection Failed: Error Code ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error(); } else { echo 'Connected and Selected'; } } }
Additional Checks
- Username Format: Double-check your username is in the format
username@servername(e.g.,troy@autosign—the servername isautosignfrom your hostautosign.database.windows.net). - Enable mysqli Extension: Open your XAMPP php.ini file and make sure
extension=mysqliis uncommented (remove the;at the start of the line). - Port Access: Ensure port 3306 is open on your local machine's firewall (Windows Defender Firewall or third-party antivirus).
内容的提问来源于stack exchange,提问作者Troy Dietrich

