Troubleshooting PHP PDO MySQL Connection Issues on Windows
This guide explains how to enable the PDO extension, configure php.ini, write connection code with proper error handling, and debug SQL statement errors to resolve common MySQL connection problems in PHP on Windows environments.
The article addresses frequent problems when connecting to a MySQL database using PHP PDO on Windows and provides a step‑by‑step troubleshooting guide.
1. Confirm PDO is enabled – PDO works on Windows with PHP 5.1+. Create a test.php file containing:
<code><?php
print phpinfo();
?></code>Running it should display PDO information; if not, edit php.ini and uncomment the lines:
<code>extension=php_pdo.dll
extension=php_pdo_mysql.dll</code>After saving, restart apache to apply the changes.
2. Database connection code – Example of creating a PDO instance and handling errors:
<code><?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=my_database', $user, $pass);
foreach ($dbh->query('SELECT * FROM student') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?></code>If a connection error occurs, a PDOException is thrown.
3. SQL statement errors – Example of an erroneous DELETE query and how to detect it:
<code><?php
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=my_database', 'root', 'root');
$sql = "delete from student"; // intentional error
$rows = $pdo->exec($sql);
if (false === $rows) {
echo 'SQL错误:<br/>';
echo '错误代码为:' . $pdo->errorCode() . '<br/>';
echo '错误原因为:' . $pdo->errorInfo()[2];
exit;
}
?></code>Use command‑line tools or GUI clients such as Navicat or phpMyAdmin to verify the SQL syntax.
Following these steps—enabling PDO, configuring the extension, writing proper connection code, and checking SQL statements—will resolve most PDO‑MySQL connection issues on Windows.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.