我在類中使用下面的方法,並調用期望格式化地址的方法。該代碼導致500錯誤。OOP的新手,試圖拉取方法的結果並顯示數據庫中的數據。獲得500錯誤
如果我刪除了try/catch
代碼塊,它將正常執行(但沒有來自數據庫的數據),並且如果我將try/catch塊放在另一頁中並使用var_dump($result)
它將顯示來自數據庫的關聯數組。
方法:
public function shippingAddress($user_id){
try{
$results = $db->prepare("SELECT address, address2, city, state, postal_code, country FROM addresses WHERE kf_user = ?");
$results->bindParam(1, $user_id);
$results->execute();
$result = $results->fetch(PDO::FETCH_ASSOC);
}catch(Exception $e){
echo "Query failed, could not connect to database.";
exit;
}
$this->street = $result['address'];
$this->street2 = $result['address2'];
$this->city = $result['city'];
$this->state = $result['state'];
$this->postal = $result['postal_code'];
if(!empty($result['country'])):
$this->country = $result['country'];
endif;
//compile variables into formatted address
//street address if address2 not set, don't include it.
$output = $this->street . "<br/>";
if(!empty($this->street2)) :
$output .= $this->street2 . "<br/>";
endif;
//city, state postal code
$output .= $this->city . ", " . $this->state . " " . $this->postal . "<br/>";
//country
$output .= $this->country;
//result
return $output;
}
其他頁面:
<?php
include_once ('inc/class.address.inc');
?>
<html>
<head>
</head>
<body>
<h1>Address:</h1>
<?php
$address = new Address;
?>
<address><?php echo $address->shippingAddress(1); ?></address>
</body>
</html>
PHP致命錯誤:調用一個成員函數準備()在數/用戶的非對象上/雅克/庫/容器/第19行的com.bitnami.mampstack/Data/app-5_4_9/apache2/htdocs/LowBidMe/inc/class.address.inc
是什麼日誌說?你有沒有設置相應的ini設置以獲得儘可能多的調試信息? – rethab
添加了日誌結果。 – Jacques
你如何初始化變量$ db?看起來像在一種情況下,它沒有正確設置。快速入侵將是使用一個函數,而不是一個變量。像get_dbconn(),然後確保這個函數在一個包含文件中。 – rethab