php连接到mysqlworkbench localhost

I have a mac with OSX 10.8.4. I have installed my localhost and it works just fine. I have made a php script, from where I would like to connect MySQL workbench database to. My apache tomcat server runs, and also mysql on the computer, and I use XAMPP. This is my code:

    <?php 

 // Establish connection to DB using PDO
 try {
  $pdo = new PDO('127.0.0.1:3306', 'root', '');
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $pdo->exec('SET NAMES "utf8"');
  echo "Connected!";
 } catch (PDOException $e) {  
  $error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
  echo "Connection failed";

  exit();
 }

I have tried this script to connect to a remote mysql server, where it works fine, but I cannot use it for my localhost. I also tried just to put in localhost in new PDO, but still the same. Does anybody have a clue to what is wrong?

Best Regards Mads

You'll have an easier time knowing what's not working if you echo the exception being thrown.

Your code

} catch (PDOException $e) {  
  $error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
  echo "Connection failed";
}

doesn't actually print the exception! Try this instead:

} catch (PDOException $e) {
    $error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
    echo $error;
}

That will at least give you some helpful debugging info.