2013-03-18 63 views
0

所以我有一個表顯示我的數據庫中的數據,我想要在總場中添加,無論如何我會得到數量和價格乘以然後顯示到新的總場?如何將PHP表中的兩個值相乘以獲得總數?

這裏是我到目前爲止的代碼

<?php 
// Connection data (server_address, database, name, poassword) 
$hostdb = 'localhost'; 
$namedb = 'xxxx'; 
$userdb = 'xxxx'; 
$passdb = ''; 

try { 
// Connect and create the PDO object 
$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb); 
$conn->exec("SET CHARACTER SET utf8");  // Sets encoding UTF-8 

// Define and perform the SQL query 
$sql = "SELECT `id`, `wine`, `amount`, `price`, `upc` FROM `wine`"; 
$result = $conn->query($sql); 

// If the SQL query is succesfully performed ($result not false) 
if($result !== false) { 
// Create the beginning of HTML table, and the first row with colums title 
$html_table = '<table border="1" cellspacing="0" cellpadding="2"><tr><th>ID</th>  <th>Wine</th><th>Amount</th><th>Price</th><th>upc</th></tr>'; 

// Parse the result set, and adds each row and colums in HTML table 
foreach($result as $row) { 
    $html_table .= '<tr><td align="center">' .$row['id']. '</td><td align="center">' .$row['wine']. '</td><td align="center">' .$row['amount']. '</td><td align="center">' .$row['price']. '</td><td align="center">' .$row['upc']. '</td></tr>'; 
} 
} 

$conn = null;  // Disconnect 

$html_table .= '</table>';   // ends the HTML table 

echo $html_table;  // display the HTML table 
} 
catch(PDOException $e) { 
echo $e->getMessage(); 
} 
?> 
<a href="/admin/">Admin</a> 
+2

'$ row ['amount'] * $ row ['price']'? – Patashu 2013-03-18 02:50:17

回答

0

喜歡這個?

'<td>' . $row['amount'] * $row['price'] . '</td>' 
0
$total_price = $row['amount'] * $row['price']; 

你還需要這些調整:

$html_table = '<table border="1" cellspacing="0" cellpadding="2"><tr><th>ID</th>  <th>Wine</th><th>Amount</th><th>Price</th><th>Total</th><th>upc</th></tr>'; 

以及循環內:

$html_table .= '<tr><td align="center">' .$row['id']. '</td><td align="center">' .$row['wine']. '</td><td align="center">' .$row['amount']. '</td><td align="center">' .$row['price']. '</td><td align="center">' .$row['upc']. '</td><td align="center">' . $total_price . '</td></tr>'; } 
0

有時顯示屏只顯示XX * XX在這種情況下,我將包裝值如下:

$total = ($row['amount']) * ($row['price']) 
0
You could easily retrieve the total by calculating it in the query itself. 

    change your sql to: 
    SELECT id, wine, amount, price, upc, (amount*price) as total FROM wine; 

    display it like this: 

    $html_table .= '<tr><td align="center">' .$row['id']. '</td><td align="center">' .$row['wine']. '</td><td align="center">' .$row['amount']. '</td><td align="center">' .$row['price']. '</td><td align="center">' .$row['upc']. '</td> 
<td align="center">' .$row['total']. '</td></tr>'; 
相關問題