0

有人可以帮我解决以下代码吗?简而言之,我试图获取两个单独的 SQL 表的数据,一个位于水平侧(品牌),另一个(分销商)位于动态填充表的垂直侧。

我的问题是,如果您浏览代码,我无法从数据库中显示的每个品牌名称下填充文本框。文本框仅出现在第一个品牌名称列中。

我的第二个问题是如何在此处为动态填充的文本框分配唯一 ID 或名称?

    <?php
$q=$_GET["q"];

include ("../connection/index.php"); 
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$sqlq="SELECT * FROM brands";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");
$resultq = mysqli_query($db,$sqlq) or die ("SQL Error_er2");

echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";
while($rowq = mysqli_fetch_array($resultq))
    {
    echo "<td>" . $rowq['bname'] . "</td>";

    }
"</tr>";

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['dname'] . "</td>";
  echo "<td><input type='text' name='txt1'></td>";
  echo "</tr>";
  }
echo "</table>";

mysqli_close($db);
?>
4

1 回答 1

0

您正在创建不相互关联的循环,执行查询也是如此......

如果要解决它,则必须将循环嵌套在一起,例如:

<?php
$q=$_GET["q"];

include ("../connection/index.php"); 
$sql="SELECT * FROM distributors WHERE rsm='".$q."'";
$result = mysqli_query($db,$sql) or die ("SQL Error_er1");

echo "<table border='1'>
<tr>
<th>Distributor</th>";
"<tr>";

//Go through all distributors
while($rowq = mysqli_fetch_array($result)) {
    echo "<td>" . $rowq['bname'] . "</td>";

    //Show all brands for current distributor
    $sqlq="SELECT * FROM brands where distributor_id = " . $rowq['rsm'];
    $resultBrands = mysqli_query($db,$sql) or die ("SQL Error Brands");

    while($row = mysqli_fetch_array($resultBrands))
    {
           $id = $row['rsm'];
        echo "<tr>";
        echo "<td>" . $row['dname'] . "</td>";
        echo "<td><input type='text' name='textBox[]'></td>";
        echo "</tr>";
    }
    //End show all brands for current distributor

}
//End Go through all distributors

不过,更好的解决方案是(当然,$q 必须在查询内部输入之前进行验证,并且还必须与 bind_param() 绑定)。

<?php
$q=$_GET["q"];

include ("../connection/index.php"); 
$sql = " SELECT * FROM distributors d";
$sql .=" LEFT JOIN brands b ON (d.brand_id = b.brand_id)";
$sql .=" WHERE d.rsm=$q";
$result = mysqli_query($db,$sql) or die ("SQL Error");

echo "<table border='1'>";

while($rowq = mysqli_fetch_array($result))
{
    $id = rowq['rsm'];
    echo "<tr>";
    echo "<td>" . $rowq['dname'] . "</td>";
    echo "<td>" . $rowq['bname'] . "</td>";
    echo "<td><input type='text' name='textBox[]'></td>";
    echo "</tr>";
}


echo "</table>";

mysqli_close($db);
?>

注意 name='textBox[]'。在 PHP 中,您可以使用 $_POST['textBox'] (或 $_GET['textBox'] 并且 PHP 将返回一个数组)访问该变量。

于 2013-03-30T14:37:03.140 回答