I've been trying to convert a mysql_connect connection into a PDO connection with no success, here is what I have:
$host = 'localhost';
$user = 'root';
$pwd = '';
$db = 'jdlferreira';
$connection = mysql_connect($host, $user, $pwd) or die("Could not connect");
mysql_select_db($db) or die("Could not select database");
$query = "SELECT COUNT(*) FROM blog";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9; // Number of pages to display. Must be odd and > 3
$pages->paginate();
$query = "SELECT id, title, resume, date
FROM blog
ORDER BY date DESC $pages->limit";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_row($result)) {
//do stuff
}
And what I tried to do with PDO:
include_once 'inc/db.inc.php';
$db = new PDO(DB_INFO, DB_USER, DB_PASS);
mysql_select_db("jdlferreira") or die("Could not select database");
$query = "SELECT COUNT(*) FROM blog";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_fetch_row($result);
$pages = new Paginator;
$pages->items_total = $num_rows[0];
$pages->mid_range = 9; // Number of pages to display. Must be odd and > 3
$pages->paginate();
$query = "SELECT id, title, resume, date
FROM blog
ORDER BY date DESC $pages->limit";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_row($result)) {
//do stuff
}
I'm getting a "Could not select database" error, I don't really care for the 'or die' cases, I would just like to make this connection functional on PDO, any help would be great.
You cant use PDO and then exepect to use mysql_*
functions they arent related.
Theres no need to select a db like that with pdo because its included in the DSN which is the contructors first argument:
$db = new PDO('mysql:host=localhost;dbname=jdlferreira', DB_USER, DB_PASS);
Then you need to use the PDO interface to interact with the DB, not the mysql ones:
$stmt = $db->prepare("SELECT COUNT(*) FROM blog");
$stmt->execute();
$num_rows = $stmt->fetchColumn();
$stmt->closeCursor();
$pages = new Paginator;
$pages->items_total = $num_rows;
$pages->mid_range = 9; // Number of pages to display. Must be odd and > 3
$pages->paginate();
$query = "SELECT id, title, resume, date
FROM blog
ORDER BY date DESC $pages->limit";
$stmt = $db->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// do stuff
}