如何在视图中将数据库中的值替换为另一个值?
假设在数据库中,'type'数据存储在数据库中是1,但在视图中我需要替换为字符串值“home loan”
这是我在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>";
答案 0 :(得分:2)
简单的if条件适用于此。
if($row['type'] == 1) {
echo "<td>home loan</td>";
} else {
echo "<td>" . $row["type"] . "</td>";
}
答案 1 :(得分: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>
答案 2 :(得分:1)
试试这个
if($row["type"]==1){
echo "<td> Home Loan </td>";
} else {
echo "<td>other type</td>";
}
希望它会有所帮助
答案 3 :(得分:0)
我喜欢这种方法:
$types = array(1=>"Home Loan");
$echo_type = isset($types[$row['type']])?$types[$row['type']]:$row['type'];
echo "<td>".$echo_type."</td>";
答案 4 :(得分: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"]) ;
}