-1

In my SQL Database, I have a table "TRANSFER" and columns with "amount_cr" and "amount_db." In my PHP Code, I have a PHP file that sends a report in the figure to $amount_cr while another file sends to $amount_db. I need a situation where a table shows the two columns using an IF Statement. That is when $amount_cr is input, let $amount_db remain blank, and vice versa.

<tr>
<th scope="col">AMOUNT CR</th>
<th scope="col">AMOUNT DB</th> 
</tr> 
<?php 
$cs_id = $_SESSION['cs_id']; 
$his = $reg_user->runQuery("SELECT * FROM transfer WHERE cs_id = '$cs_id' ORDER BY id DESC LIMIT 3"); 
$his->execute(array(":cs_uname" => $_SESSION['cs_uname'])); 
while($rows = $his->fetch(PDO::FETCH_ASSOC))
?> 

// I tried the following as a newbie
<tr> 
<td style="color:green;" scope="row">+ $ <?php echo $rows['amount_cr']; ?></td>
<td style="color:red;" scope="row">- $<?php echo $rows['amount_db']; ?></td>
</tr>

This is what I get as the output enter image description here

I wish to have the output this way enter image description here

Amount (Credit) | Amount (Debit)

When the incoming input is for amount_cr, it appears on the amount_cr column while amount_db remain blank, vice versa. Like what I have on the Image

2
  • PHP like most languages has a concept of if statements. These are program flow control structures. You can use an if statement to conditionally display the value. Commented Dec 14, 2024 at 15:27
  • Did you make a mistake here '$cs_id'? It should be :cs_uname or something like that Commented Dec 14, 2024 at 15:28

1 Answer 1

0

Added if, else condition inside while loop to display blank space when value is 0 for credit or debit.

   <tr>
  <th scope="col">AMOUNT CR</th>
  <th scope="col">AMOUNT DB</th>
</tr> 

<?php 
$cs_id = $_SESSION['cs_id']; 
$his = $reg_user->runQuery("SELECT * FROM transfer WHERE cs_id = :cs_id ORDER BY id DESC LIMIT 3"); 
$his->execute(array(":cs_id" => $cs_id)); // Changed to use prepared statement for cs_id

while($rows = $his->fetch(PDO::FETCH_ASSOC)) {
?> 

<tr> 
  <!-- Display amount_cr if it exists -->
  <td style="color:green;" scope="row">
    <?php 
      if (!empty($rows['amount_cr'])) {
        echo "+ $ " . $rows['amount_cr']; 
      } else {
        echo "-"; // Blank if no amount_cr value
      }
    ?>
  </td>
  
  <!-- Display amount_db if it exists -->
  <td style="color:red;" scope="row">
    <?php 
      if (!empty($rows['amount_db'])) {
        echo "- $ " . $rows['amount_db']; 
      } else {
        echo "-"; // Blank if no amount_db value
      }
    ?>
  </td>
</tr>

<?php 
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. It worked Pefectly for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.