2013-08-02 111 views
0

如何在視圖中將數據庫中的值替換爲另一個值?PHP Mysql替換while循環中的值

讓數據庫說,存儲在數據庫中「類型」的數據是1,但鑑於在我需要更換爲字符串值「住房貸款」

Sample data in database

這是我在PHP代碼:

$loans = mysql_query("SELECT * FROM loans"); 

echo "<table cellspacing='2'>"; 

echo "<tr><th>ID</th><th>Name</th><th width=70>Type</th><th width=70>Amount</th><th width=70>Duration</th><th>Installment</th><th></th><th></th></tr>"; 
?> 
<form method="post" action=""> 
<?php 
while ($row = mysql_fetch_array($loans)) { 

    echo "<tr>"; 

    echo "<td>" . $row["loan_id"] . "</td>"; 

    echo "<td>" . $row["name"] . "</td>"; 

    echo "<td>" . $row["type"] . "</td>"; 

    echo "<td>" . $row["amount"] . "</td>"; 

    echo "<td>" . $row["duration"] . "</td>"; 

    echo "<td>" . $row["installment"] . "</td>"; 

    echo "</tr>"; 

} 

echo "</table>"; 

回答

1

試試這個

if($row["type"]==1){ 
    echo "<td> Home Loan </td>"; 
    } else { 
    echo "<td>other type</td>"; 
    } 

希望這將有助於

+0

THX它解決了:) – Kamalisto

2

一個簡單的條件將適用於此。

if($row['type'] == 1) { 
    echo "<td>home loan</td>"; 
} else { 
    echo "<td>" . $row["type"] . "</td>"; 
} 
0

我喜歡這種方法:

$types = array(1=>"Home Loan"); 

$echo_type = isset($types[$row['type']])?$types[$row['type']]:$row['type']; 
echo "<td>".$echo_type."</td>"; 
0
while ($row = mysql_fetch_array($loans)) { 

    printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",$row["loan_id"],$row["name"], ((int)$row["type"] === 1 ? 'home loan':'other'),$row["amount"], $row["duration"], $row["installment"]) ; 
} 
2

您應該創建與每種類型的相關值,另一個表,並加入上表中的值。

表loan_types

id | loan_type 
1 | Home Loan 
2 | Other Loan 

然後將查詢

<?php 
$loans = mysql_query("SELECT loans.*, loan_types.`loan_type` FROM loans LEFT JOIN loan_types ON loans_types.`id` = loans.`type`"); 
?> 

<table cellspacing='2'> 
    <tr> 
     <th>ID</th> 
     <th>Name</th> 
     <th width=70>Type</th> 
     <th width=70>Amount</th> 
     <th width=70>Duration</th> 
     <th>Installment</th> 
    </tr> 
    <?php while ($row = mysql_fetch_array($loans)) { ?> 
    <tr> 
     <td><?php echo $row["loan_id"]; ?></td> 
     <td><?php echo $row["name"]; ?></td> 
     <td><?php echo $row["loan_type"]; ?></td> 
     <td><?php echo $row["amount"]; ?></td> 
     <td><?php echo $row["duration"]; ?></td> 
     <td><?php echo $row["installment"]; ?></td> 
    </tr> 
    <?php } ?> 
</table>