[函数在尝试重复代码时会中断页面

问题描述 投票:1回答:1

我是新手开发人员。有此代码:

<?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
    }
?>

来自第二个文件的代码

<?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
    }
?> 

您可以看到,有被html“打断”的php代码,然后通过关闭while循环的花括号来继续。

问题是我需要重复php代码,而不是html。下次运行php时,内部的html代码将有所不同(在html内有回显函数,这些函数从循环结果中检索不同的数据)。

我尝试将第一段代码放入函数中并运行该函数,但它只会弄乱页面的布局,而没有显示代码应呈现的部分。

我的问题是:如何重用第一部分不完整的代码?谢谢!

php function loops
1个回答
2
投票

不是启动和停止PHP代码,而是只是简单地回显要包含的HTML代码吗?它可以帮助您组织循环中要重复的内容和不重复的内容。这是一个例子:

$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())
    {   
        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
© www.soinside.com 2019 - 2024. All rights reserved.