将行的id存储在mysql中的选项选择列表中


store the id of a row on the option selected list from mysql

我将一行的属性列表从一个表中回显到一个选项列表中,供用户从中选择,稍后将用于插入另一个表。我想做的是,单独存储该行的"id"(不使用外键),但我一直得到的"id"是列表上最后一行的"id"。以下是我的代码片段:

        <?php
        $conn = mysqli_connect('localhost', 'root', '', 'database');
          $result = mysqli_query($conn, "SELECT * FROM myTable WHERE region = '{$thisRegion}' ");
          //$result .= " ");
          while ($row = mysqli_fetch_assoc($result))
          {
            $selected = (isset($_POST['list']) && $_POST['list'] ==  $row['id']) ? 'selected' : '';
              echo "<option value='$row[streetAddress] $row[apt] $row[city] $row[zip] $row[_state] $row[country]' $selected >$row[city] $row[zip] $row[_state] $row[country] $row[streetAddress] $row[apt]</option>";
              $thisId= $row['id'];
              $_SESSION["thisId"] = $thisId;
          }
          ?>
        </select>

您的问题在于代码

while ($row = mysqli_fetch_assoc($result))
{
    ...
    $thisId= $row['id'];
    $_SESSION["thisId"] = $thisId;
}

这段代码意味着,在每次迭代中,$_SESSION["thisId"]将被替换为当前行的id,这样在循环结束时,只有最后一行的id才会出现。

我认为这样做的方法是将id添加到选项中,并将行打印为显示。

echo "<option value='{$row['id']}'> {$row['apt']} {$row['city']}... </option>";

然后,接收页面可以读取

$selectedRowId = $_GET['optionKey']

我希望这会有所帮助,您应该阅读更多关于php和表单的内容,因为这将使您的编码更容易。这里有一个基本教程http://www.w3schools.com/php/php_forms.asp