Why does my PDO MySQL connect not work?

C++, C#, Java, PHP, ect...
Post Reply
User avatar
Verahta
Posts: 440
Joined: Wed Aug 24, 2011 1:50 am

Why does my PDO MySQL connect not work?

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


?>

"In order to understand recursion, one must first understand recursion".
User avatar
Verahta
Posts: 440
Joined: Wed Aug 24, 2011 1:50 am

Re: Why does my PDO MySQL connect not work?

Post 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.
"In order to understand recursion, one must first understand recursion".
Post Reply

Return to “Coding”