2016-05-16 202 views
0

我還在學習PHP OOP和英語。
我不知道如何從數據庫返回結果。我寫了方法,返回結果:從數據庫返回結果PHP OOP

class Serial extends DbUser { 

public $history, $sn, $added, $numrows; 

function __construct() { 
    parent::__construct('localhost', 'michal', '', 'test'); 

} 

function historyProduct($sn) { 
    $result = $this->history = $this->conn->prepare("SELECT * FROM `products` WHERE sn = ?"); 
    $result = $this->history->bind_param('s', $sn); 
    $result = $this->history->execute(); 
    $result = $this->history->get_result(); 
    return $result; 
    while ($row = mysqli_fetch_array($result)) { 
     $this->sn = $row['sn']; 
     $this->added = $row['added']; 
    } 
    $this->numrows = mysqli_num_rows($result); 

} 

function __toString() { 
    return (string) $this->numrows; 
} 

} 

$sn = $_GET['sn']; 
$history = new Serial(); 
$history->historyProduct($sn); 
printf($history); 
echo $history->added; 

但是這種方法不會顯示任何東西。

我試過這個: return values from class php oop
我在做什麼錯了?

Michał。

+0

你方法中的'return $ result;'這一行幾乎確保沒有爲該類的'added'和'numrows'屬性設置任何東西; – YvesLeBorg

回答

0

一個php函數只會處理,直到它到達一個return語句。這與例如「休息」有相同的效果。除了它返回的值。

如果您希望執行while子句,則必須將return語句放在方法的最後。

爲了更好的可讀性,我建議你設置一次結果值,而不是每一個$ this-> history方法調用。