這是在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