2011-08-26 21 views
6

這是我當前頁面:使用PDO替換mysql_connect - 格式正確嗎?

<?php 

mysql_connect('localhost', 'root', 'mypass') or die (mysql_error()); 
mysql_select_db('radio1') or die (mysql_error()); 
$result = mysql_query("SELECT *, TIME_FORMAT(airtime, '%H:%i') `airtime` 
from presenters"); 
//Table starting tag and header cells 
while($row = mysql_fetch_array($result)) { 
?> 
    <?php foreach($rows as $row):?> 
     <dl class="standard"> 
      <dt><a href="<?=$row=['link'] ?>" title="<?=$row=['presenter'] ?>"><?=$row['airtime'] . " - " .$row['presenter']?></a></dt> 
      <dd class="itemimg"><a href="<?=$row=['link'] ?>" title="<?=$row=['presenter'] ?>"><img src="<?=$row['image']; ?>" width="100" height="75" alt="<?=$row=['presenter'] ?>" title="<?=$row=['presenter'] ?>" /></a></dd> 
      <dd class="itemdesc"> 
       <?=$row['showinfo']; ?> 
      </dd> 
      <dd class="itemlink"> 
       <a href="<?=$row=['link'] ?>" title="Find out more..."><span> </span> 
         <?=$row['more']; ?></a> 

      </dd> 
     </dl> 
    <?php endforeach;?> 

我想將其轉換爲與PDO運行的代碼,因爲它在我的php.ini啓用

我怎麼會得到PDO與這方面的工作,正如我打算(爲這個項目和所有未來的項目)逐步淘汰使用舊的mysql_connect。

我看了一下如何在Zend Developer Zone做到這一點,雖然我可以在一個平均水平爲基礎Dwoo的項目去做,這個模板使用模板引擎 - 它是純粹的基於PHP語法,沒有使用模板,只需要各種include()並需要加上echo()

任何幫助表示讚賞!

+1

請顯示你的嘗試。這很無聊,只爲你寫。 – xdazz

+0

@xdazz - 代碼位於http://pastebin.com/atJF6TcZ – radiogeek86

+2

您應該仔細閱讀有關pdo的手冊。這就是我學習的方式,並花了我十分鐘的時間掌握基礎知識。它也有如何正確使用它的很好的例子。從mysql轉換爲pdo的+1。 [手動輸入PDO](http://www.php.net/manual/en/book.pdo.php) –

回答

4

這是您的解決方案。

<?php 

$hostname = "localhost"; 
$username = "root"; 
$password = "mypass"; 
$dbname = 'radio1'; 
$dbh =null; 
try { 
    $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); 
} 
catch(PDOException $e) 
{ 
    echo $e->getMessage(); 
} 

$result = $dbh->query("SELECT *, TIME_FORMAT(airtime, '%H:%i') `airtime` from presenters"); 
//Table starting tag and header cells 
while($row = $result->fetch()) { 
?> 
<?php foreach($rows as $row):?> 

    <dl class="standard"> 
    <dt><a href="<?=$row=['link'] ?>" title="<?=$row=['presenter'] ?>"><?=$row['airtime'] . " - " .$row['presenter']?></a></dt> 
     <dd class="itemimg"><a href="<?=$row=['link'] ?>" title="<?=$row=['presenter'] ?>"><img src="<?=$row['image']; ?>" width="100" height="75" alt="<?=$row=['presenter'] ?>" title="<?=$row=['presenter'] ?>" /></a></dd> 
      <dd class="itemdesc"> 
        <?=$row['showinfo']; ?> 
       </dd> 
       <dd class="itemlink"> 
      <a href="<?=$row=['link'] ?>" title="Find out more..."><span> 
</span> 
    <?=$row['more']; ?></a> 

        </dd> 
</dl> 
<?php endforeach;?> 
-1

使用開發代碼如下

//在代碼結束時,你必須釋放的資源

//免費使用的資源

$ result-> closeCursor();

$ dbh = null;