2012-09-17 69 views
0

我一直在嘗試將連接的mysql_connect與沒有成功PDO連接轉換,這裏是我有:的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上起作用,任何幫助都會很棒。

回答

3

您不能使用PDO,然後使用mysql_*來執行它們沒有關聯的功能。

世界上沒有必要選擇這樣的一個數據庫與PDO,因爲它包含在其中是contructors第一個參數的DSN:

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

然後,你需要使用PDO接口與數據庫進行交互,而不是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 
    } 
+0

我有什麼機會或在PDO中制定出同等的解決方案?我一直在尋找PHP網站上的mysql_ *函數,並且我找不到對等的運氣。 –

+0

如果你想要等價的話,'mysqli'庫與舊的'mysql'庫比PDO更接近。但請閱讀這個答案給出的例子 - 他給了你一個非常可靠的例子,告訴你如何去做你在PDO中要求的東西:你需要的所有電話都在那裏。 – Spudley

+0

很好的解決方案,感謝您的幫助,我得到這個錯誤: 致命錯誤:調用未定義的方法PDOStatement :: close(),我刪除了那個close();線和一切似乎運作良好,我在這裏錯過了什麼?我沒有關閉$ stmt有什麼問題? –