mysql_connect到PDO连接

时间:2012-09-17 21:06:11

标签: php pdo mysql-connect

我一直在尝试将mysql_connect连接转换为PDO连接但没有成功,这就是我所拥有的:

$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
}

我试图用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
}

我收到了“无法选择数据库”的错误,我并不关心'或死'的情况,我只想让这个连接在PDO上运行,任何帮助都会很棒。

1 个答案:

答案 0 :(得分:3)

您无法使用PDO,然后尝试使用与它们无关的mysql_*函数。

Theres无需选择与pdo类似的db,因为它包含在DSN中,这是构造函数的第一个参数:

$db = new PDO('mysql:host=localhost;dbname=jdlferreira', DB_USER, DB_PASS);

然后你需要使用PDO接口与DB交互,而不是mysql:

    $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
    }