Databases 3 min read

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.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Troubleshooting PHP PDO MySQL Connection Issues on Windows

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>&lt;?php
print phpinfo();
?&gt;</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>&lt;?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();
}
?&gt;</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>&lt;?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;
}
?&gt;</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.

mysqlTroubleshootingWindowsdatabase-connection
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.