Why does my PDO MySQL connect not work?
Posted: Tue Apr 17, 2012 5:32 pm
My PDO MySQL connect does not work, and PDO is enabled for MySQL in my PHP ini file. In the code below, the commented out connect works, and the PDO one does not. Any idea why?
Here is my test page that works with the regular connect, but not the PDO one. I keep getting the "could not select user!" error on the 3rd line of code.
Code: Select all
<?php
/* this regular connect works fine...but the PDO version below does not.
$db = mysql_connect("localhost","root","pass") or die("Could not connect to db.");
if(!$db)
die("no dice! no db found.");
if(!mysql_select_db("db",$db))
die("No DB selected.");
*/
$host = "localhost";
$db_name = "db";
$username = "root";
$password = "pass";
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //TO handle connection error
echo "Connection error: " . $exception->getMessage();
}
?>
Here is my test page that works with the regular connect, but not the PDO one. I keep getting the "could not select user!" error on the 3rd line of code.
Code: Select all
<?php
include 'connect.php';
$userinfo ="SELECT name FROM users WHERE id=1 ";
$userinfo2 = mysql_query($userinfo) or die ("could not select user!");
$userinfo3 = mysql_fetch_array($userinfo2);
echo "User1's name is " . $userinfo3['name'];
?>