问题
This is my current page:
<?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;?>
I want to convert this to code that works with PDO, since it is enabled in my php.ini
How would I get PDO to work with this, as I'm intending on (for this project and all future ones) phasing out use of the older mysql_connect.
I had a look at how to do it at the Zend Developer Zone and although I can do it at an average level for Dwoo-based projects, this template does not use a templating engine - it is pure PHP-based syntax, no templates used, only various include()
and require, plus echo()
where needed.
Any help is appreciated!
回答1:
Here is your solution.
<?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;?>
来源:https://stackoverflow.com/questions/7207427/using-pdo-to-replace-mysql-connect-formatting-correctly