1
\$\begingroup\$

I am not a expert on php html. I built a website 2 months ago, and realized I using lot of php query result on web. Is there any approach without while my query result on multiple times

<table>
<tbody>
<?php 
$proc = "{call p_rpt_str310Web (?,?,?)}";
$params = array($PlanPkID,$bycatID,$ByDateVal);  
$result = sqlsrv_query($conn, $proc, $params);
while ($row = sqlsrv_fetch_array($result))
{   
?>
<tr>
<td><?php echo $count; ?></td>
<td class="alignLefter"><?php echo $row['CusName']; ?></td>
<td><?php echo $row['CusCount']; ?></td>
<td><?php echo $row['WorkTime']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>

I have code like this in my html multiple times is there any way to do something like this

\$\endgroup\$
1
\$\begingroup\$

There are many ways to improve this code. but the two most basic ones would be

  1. To create a simple helper function in order to avoid the repetitive code when running a query.
  2. To separate the database interaction from the presentation logic, making the application more flexible, maintainable and clean-looking.

And one way of improvement I would advise against of: a function that would automate the HTML table creation. Although for the most primitive cases it would do, in reality there are no primitive cases, and you'll end up with a monster that takes more code to configure than to write just plain HTML, and it would completely unreadable compared with a straightforward HTML template.

A function.

function sqlsrv($conn, $sql, $params)
    $result = sqlsrv_query($conn, $sql, $params);
    $return = [];
    while ($row = sqlsrv_fetch_array($result)) {
        $return = $row;
    }
}

this function accepts a connection, an arbitrary query and an array of parameters, and returns a simple array with returned rows.

You can put this function's definition into the same file where your connection is made.

Code separation

This one is simple. Always split your scripts into two parts: data manipulation (AKA business logic) and a template (aka presentation logic). So you can refactor your code like this

$data = sqlsrv($conn, "{call p_rpt_str310Web (?,?,?)}",[$PlanPkID,$bycatID,$ByDateVal]);
?>

<table>
  <tbody>
    <? php foreqach ($data as $row): ?>
    <tr>
      <td><?= $count ?></td>
      <td class="alignLefter"><?= $row['CusName'] ?></td>
      <td><?= $row['CusCount'] ?></td>
      <td><?= $row['WorkTime'] ?></td>
    </tr>
    <?php endforeach ?>
  </tbody>
</table>
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.