0

如何在查看期间将数据库中的值替换为另一个值?

假设在数据库中,存储在数据库中的“类型”数据为 1,但在查看期间我需要替换为字符串值“房屋贷款”

数据库中的样本数据

这是我在 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>";
4

5 回答 5

2

一个简单的 if 条件将适用于此。

if($row['type'] == 1) {
    echo "<td>home loan</td>";
} else {
    echo "<td>" . $row["type"] . "</td>";
}
于 2013-08-02T04:46:31.323 回答
2

您应该使用与每种类型关联的值创建另一个表,并将该值连接到该表上。

表贷款类型

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>
于 2013-08-02T04:56:28.410 回答
1

尝试这个

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

希望它会有所帮助

于 2013-08-02T04:46:04.023 回答
0

我喜欢这种方法:

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

$echo_type = isset($types[$row['type']])?$types[$row['type']]:$row['type'];
echo "<td>".$echo_type."</td>";
于 2013-08-02T04:48:48.337 回答
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"]) ;
}
于 2013-08-02T04:49:56.143 回答