phppdo¿我做错了什么?

I'm learning php pdo; my environment is : NetBeans 6.5.1, XAMPP 1.7.0 and I have this code, which it seems to connect.

  • If I change dbname to a non existent one, it raises exception "db not exists"
  • If I change user, it raises "login incorrect")

but when I call $cn->query, it raises:

An unhandled Win32 exception occurred in apache.exe

What am I doing wrong?

$hostname = 'localhost';
$username = 'crb';
$password = 'letmein';
try {
    $cn = new PDO("mysql:host=$hostname;dbname=bitacora", $username, $password);
    echo 'Connected to database<br />';
    $sql = "SELECT * FROM usuario WHERE login = '".$login."' AND clave = '".$clave."'";
    // Error here
    foreach ($cn->query($sql) as $row) {
        print $row['login'] .' - '. $row['clave'] . '<br />';
    }
} catch (PDOException $e) {
    echo $e->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

This is a bug in XAMPP 1.7.0. Upgrade to 1.7.1 or follow these instructions to fix your 1.7.0 installation.

Is $cn valid? Check the return value. What you've described so far doesn't convince me that you're connected.

If you haven't already, I'd make sure your environment was working right.

  1. Check to make sure the user works with MySQL itself (using something like mysqlquery).
  2. Check to make sure php can connect to MySQL. I install phpmyadmin on all new setups (even if I don't leave it in place) to make sure I have a good working connection.
  3. Have PDO through exceptions on errors (see http://us2.php.net/manual/en/pdo.error-handling.php) to see where the errors are occurring right away.

My guess is that you are not ever connecting to MySQL, which would explain the inability to change the database.