这是在Using PDO to replace mysql_connect - formatting correctly?PHP echo和PDO - 如何解决成员函数查询错误?
这是本身将被回显到另一个页面较大的页面的一部分,我刚才的问题的延续
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = 'MYPASSWORD';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=radiotest", $username, $password);
/*** echo a message saying we have connected ***/
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM presenters";
foreach ($dbh->query($sql) as $row)
{
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<?php foreach ($dbh->query($sql) as $row) ?>
<table>
<td>
<tr><?php echo $row['presenter'] ?><?php echo $row['show'] ?> </tr>
</table>
它给了这个错误:
Fatal error: Call to a member function query() on a non-object in C:\www\vhosts\localhost\radio1.php on line 29
我想避免这个错误,并能够回显行,如果我可以...不使用此代码(我的原始编码 - 它的工作,但我试图使用PDO与回声如上例):
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = 'MYPASSWORD';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=radiotest", $username, $password);
/*** echo a message saying we have connected ***/
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM presenters";
foreach ($dbh->query($sql) as $row)
{
echo $row['presenter'] .' - '. $row['show'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
什么可能导致此错误,为什么?
我应该用代码做保证,这是循环:
<table>
<td>
<tr><?php echo $row['presenter'] ?><?php echo $row['show'] ?> </tr>
</table>
基本上,我试图用PDO来代替的mysql_connect的回响在HTML表中的行或定义列出了我测试网站。
下面是编辑后的版本现在:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = 'MYPASSWORD';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=radiotest", $username, $password);
/*** echo a message saying we have connected ***/
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM presenters";
foreach ($dbh->query($sql) as $row)
{
echo $row['presenter'] .' - '. $row['show'] . '<br />';
}
/*** close the database connection ***/
$dbh;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
<table>
<td>
<tr><?php echo $row['presenter'] ?><?php echo $row['show'] ?> </tr>
</table>
它显示的数据,但不低于表中。
1)在关闭try块中的连接之前创建表格内容。 || 2)用'$ dbh = null'关闭页面底部的连接。 – afuzzyllama