使用PDO替换mysql_connect - 正确格式化?

时间:2011-08-26 15:55:55

标签: php mysql pdo echo

这是我目前的页面:

<?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()和require,加上echo()

感谢任何帮助!

1 个答案:

答案 0 :(得分: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;?>