Message if table empty

Hi,

I have a database table. If the table is empty i just want to display a simple message.

Here is my code.

	<?php if (!empty($cis_data)) { ?>

	<?php $total = 0; ?>

	<?php foreach($cis_data as $deductions) { ?>

	<?php $total += $deductions['deduction_amount']; ?>

	<?php } ?>

	<?php if (!empty($total)) { ?>



	<input type='button' id='print-page' value='Print' onclick='window.print();'>

	<div>

		<p><?php echo htmlspecialchars($_SESSION['login']['customer_name']); ?></p>

			<p><?php echo htmlspecialchars($_SESSION['login']['company_name']); ?></p>


			<p class="total">2022 To 2023 : Total CIS Deductions<br> <b>&pound<?php echo $total; ?></b><br></p>






			<table class="printable-table">



			
				<tr>

					<th>Deduction date</th>

								

					<th>Deduction amount</th>

					

				</tr>

			
			<tbody>


			<?php foreach($cis_data as $deductions) { ?>



				<tr>

					<?php $date_created = new DateTime($deductions['date_created']); ?>

					<td><?php echo $date_created->format('d M Y'); ?></td>



					<td><?php echo htmlspecialchars($deductions['deduction_amount']); ?></td>



				</tr>



			<?php } ?>



			</tbody>

			</table>

		<?php } ?>

	<?php } ?>

	</div>

</div>

Wouldn’t you just add an else { … } to the existing conditional logic?

Here’s are some of tips -

  1. Why are you putting opening and closing php tags around each line of code within a single block of php code? That just clutters up your code with unnecessary typing and typo mistakes. Just use one opening and one closing php tag around the whole block of php code.
  2. When the conditional logic failure/false code is much shorter then the success/true code, if you invert the condition being tested and put the failure/false code in the if (){} part of the conditional statement, then put the success/true code in the else {} part of the conditional statement, your code will be much easier to read.
  3. The code getting the $total can be greatly simplified by using array_sum and array_column -
$total = array_sum(array_column($cis_data,'deduction_amount'));
Sponsor our Newsletter | Privacy Policy | Terms of Service