Php 使用for循环获取会话数组和现有表值的值

Php 使用for循环获取会话数组和现有表值的值,php,arrays,loops,session-variables,Php,Arrays,Loops,Session Variables,我写了一个表单,它有10个相同的输入,存储在一个数组中,以循环并相应地操作数据。带有输入的表单示例: <form id="sanFiber" action="insert.php" method="post"> <table class="frame"> <tr> <td><input name="host[]" class="field" type="text" size="15"

我写了一个表单,它有10个相同的输入,存储在一个数组中,以循环并相应地操作数据。带有输入的表单示例:

    <form id="sanFiber" action="insert.php" method="post">
    <table class="frame">
    <tr>
        <td><input name="host[]" class="field" type="text" size="15" 
           <?php if(isset($_SESSION['hostName'])){ echo "value='
           ".$_SESSION['hostName']."'";}?> /></td>
    </tr>
    <tr>
        <td><input name="host[]" class="field" type="text" size="15" 
        <?php if(isset($_SESSION['hostName'])){ echo"value='".$_SESSION['hostName']."'";}?> /></td>
   </tr>
       ...
   </form>
我已经能够创建for循环,以便在数据库上的现有表中插入新值,但是,我在尝试以相同的方式执行Select查询时遇到了困难,因为这些值不是预先存在的。我尝试的循环只返回第一个值。冲突在于我必须循环会话数组和数据库中找到的行。$row值的for循环部分工作正常。会话循环是我的问题所在。我的Select查询和for循环如下:

<?php 
include ("connect.php");
session_start();

$query = "SELECT * FROM cable_request_san_fiber_detail WHERE cable_request_id = '".$id."'"; 

$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    $label[]=$row['cable'];
}       
for ($i=0, $n=0; $i<count($label), $n<count($_SESSION['hostName']); $i++, $n++){
    $_SESSION['hostName'][$n]=$label[$i];
}
    header('Location:Table.php');
$conn->close();
?>

在for循环中,我组合了两个不同的循环:一个用于计算和循环所有会话变量,另一个用于循环数据库表中的所有行。是否有任何方法可以正确地同时执行这两个for循环,还是应该分别执行它们?

您在一个数组中……尝试将数组作为字符串进行回显。在循环中do echo$res=array\u shift$\u SESSION['hostName']?$res:

拥有$label有意义吗

而不是:

while ($row = mysqli_fetch_assoc($result)) {
    $label[]=$row['cable'];
}       
for ($i=0, $n=0; $i<count($label), $n<count($_SESSION['hostName']); $i++, $n++){
    $_SESSION['hostName'][$n]=$label[$i];
}
以HTML格式输出时,您可能希望在数组中循环:

<?php
foreach($_SESSION['hostName'] as $hostname) {
?>
    <tr>
        <td>
            <input name="host[]" class="field" type="text" size="15" value="<?= $hostname ?>" />
        </td>
    </tr>
<?php
}
?>

在第一个块中,您将以字符串形式回显$\u会话['hostName']。那么,为什么要在第二块中的$_会话['hostName']上创建一个数组呢?@Devon Oh..我明白你的意思了。但是我需要会话是一个数组,因为有多个输入值。我是否应该在第一个块中将其作为字符串进行回显,而在循环中将会话作为数组进行回显?因此,我的for循环应该更像。。对于$i=0,$n=0$label变量用于循环电缆标签行$row的表值['cable'但是,你的单循环很有意义,看起来不那么混乱。我明天会在服务器上试用并测试它,然后告诉你结果。谢谢你的帮助!将它标记为有效答案。你的循环帮助我获得了每个会话数组值,没有任何错误,并简化了我自己的循环。
<?php
foreach($_SESSION['hostName'] as $hostname) {
?>
    <tr>
        <td>
            <input name="host[]" class="field" type="text" size="15" value="<?= $hostname ?>" />
        </td>
    </tr>
<?php
}
?>