2017-09-04 60 views
0

我想顯示一些存儲在MySQL表中的特定客戶的交易記錄。如何在PHP-MySQL中以降序獲取特定客戶的交易記錄?

我試過follwing:

<table> 
<tr> 
    <th>Transaction ID</th> 
    <th>Customer ID</th> 
    <th>Description</th> 
    <th>Amount</th> 
    <th>Date</th> 
</tr> 
<?php 
    $stmt0 = $mysqli->prepare("SELECT id FROM customers WHERE status = ?"); 
    $stmt0->bind_param('i',$status); 
    $stmt0->execute(); 
    $stmt0->store_result(); 
    $stmt0->bind_result($cust_id); 
    while ($stmt0->fetch()) 
    { 
     $stmt = $mysqli->prepare("SELECT id,description,amount,date FROM transactions WHERE cust_id = ? ORDER BY id DESC"); 
     $stmt->bind_param('i',$cust_id); 
     $stmt->execute(); 
     $stmt->store_result(); 
     $stmt->bind_result($id,$description,$amount,$date); 
     while ($stmt->fetch()) 
     { 
?> 
<tr> 
    <td><?php echo $id; ?></td> 
    <td><?php echo $cust_id; ?></td> 
    <td><?php echo $description; ?></td> 
    <td><?php echo $amount; ?></td> 
    <td><?php echo $date; ?></td> 
</tr> 
<?php 
     } 
     $stmt->close(); 
    } 
     $stmt0->close(); 
?> 
</table> 

它顯示了特定客戶的交易記錄,按我的要求,但它通過「CUST_ID」分組顯示的記錄。我需要按降序排列「id」來顯示它們。

請幫忙!

+0

你的意思是通過訂購'id'整個列表中'cust_id'不論降序排列? –

+0

@pro_cheats yes .. –

回答

0

您可以使用SUB QUERIES並在一個SQL語句本身中獲取結果。 像 -

<?php 
    $stmt0 = $mysqli->prepare("SELECT t.id,t.description,t.amount,t.date FROM transactions t WHERE t.cust_id = (SELECT id FROM customers WHERE status = ?) ORDER BY t.id DESC"); 
    $stmt0->bind_param('i',$status); 
    $stmt0->execute(); 
    $stmt0->store_result(); 
    $stmt0->bind_result($id,$description,$amount,$date); 
    //PRINT/echo $id,$description,$amount,$date to the front end now 
?> 

這應該降$id的順序返回$id,$description,$amount,$date值。

另一種方法是使用SQL JOINS(優於子查詢儘管內部執行幾乎是相同的)

$stmt0 = $mysqli->prepare("SELECT t.id,t.description,t.amount,t.date FROM transactions t INNER JOIN customers c on t.cust_id=c.id WHERE c.status = ? ORDER BY t.id DESC"); 
//rest of the code remains same 
+0

這兩種方法都很好用!再次感謝! –

相關問題