Page 1 of 1

Why does my PDO MySQL connect not work?

Posted: Tue Apr 17, 2012 5:32 pm
by Verahta
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?

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'];


?>


Re: Why does my PDO MySQL connect not work?

Posted: Fri Apr 20, 2012 6:38 am
by Verahta
Nevermind, I figured it out. MySQL/MySQLi/PDO all use a little bit different syntax and you can't mix them together. I thought PDO was just a way to connect to the database, but I see now it is an entirely alternative way to code PHP/MySQL and is not compatible in combination with MySQL/MySQLi.