Reputation: 53
I'm a newbie developer. There is this code:
<?php
$sql_client = "SELECT * FROM clienti WHERE nume = ? LIMIT 1";
$stmt_client = $conn->prepare($sql_client);
$stmt_client->bind_param("s", $nume);
$stmt_client->execute();
$result_client = $stmt_client->get_result();
while($row = $result_client->fetch_assoc())
{
?>
<td style="width:35%;">
<b>Cumpărător</b>:<br>
<?php echo $row["nume"]; ?><br>
<b>Nr Orc</b>: <?php echo $row["reg_com"]; ?><br>
<b>CIF</b>: <?php echo $row["cif"]; ?><br>
<b>Sediu</b>:<br>
<?php echo $row["adresa"]; ?><br>
<b>Banca</b>:<br>
<?php echo $row["banca"]; ?><br>
<b>Cont bancar</b>:<br>
<?php echo $row["cont_bancar"]; ?><br>
</td>
</tr>
</table>
<?php
}
?>
Code from second file
<?php
$sql_client = "SELECT * FROM clienti WHERE nume = ? LIMIT 1";
$stmt_client = $conn->prepare($sql_client);
$stmt_client->bind_param("s", $nume);
$stmt_client->execute();
$result_client = $stmt_client->get_result();
while($row = $result_client->fetch_assoc())
{
?>
Am încasat de la <?php echo $row["nume"]; ?> <br>
Nr ORC/an: <?php echo $row["reg_com"]; ?> <br>
CIF: <?php echo $row["cif"]; ?><br>
Adresa: <?php echo $row["adresa"]; ?> <br>
<?php
}
?>
As you can see, there's php code that is "interrupted" by html, then it continues by closing the curly brace of the while loop.
The problem is that I need to repeat the php code but not the html. The html code from within will be different the next time php runs (inside the html there are echo functions that retrieve different data from the loop results).
I tried putting the first chunk of code inside a function and run the function but it only screws up the layout of the page and doesn't show the part that the code should render.
My question is: how can I reuse that first chunk of incomplete code? Thank you!
Upvotes: 1
Views: 72
Reputation: 1934
Instead of starting and stopping your PHP code, have you looked at simply echoing the HTML code that you want to include? It might help you organize what you want repeated in the loop and what you do not. Here's an example:
$myArray = []; //array that will hold the values you get from database for later use
$sql_client = "SELECT * FROM clienti WHERE nume = ? LIMIT 1";
$stmt_client = $conn->prepare($sql_client);
$stmt_client->bind_param("s", $nume);
$stmt_client->execute();
$result_client = $stmt_client->get_result();
echo '<table>'; //does not repeat
while($row = $result_client->fetch_row())
{
array_push($myArray, $row); //add each row to an array outside the scope of your loop
echo '<tr>'; //repeats once for each table row
foreach($row as $columnValue){
echo '<td><p>'.$columnValue.'</p></td>'; //repeats for every value in table
}
echo '</tr>';
}
echo '</table>'; //does not repeat
echo $myArray[0][0]; //echo first value of first row
Upvotes: 2