dongyinshua9996 2013-07-16 19:11
浏览 30
已采纳

如何在没有定义列的html表中显示sqli select查询结果

I want to display the results of my select query on my webpage in a table, however the code im using at the moment uses a pre-defined set of columns. My code is this:

   $result= mysqli_query($con,"SELECT * FROM Customers where First_name = '$specFirstName'");

echo "<table border=\"1px solid black\" width=\"80%\"><tr><th>Customer ID</th><th >First Name</th><th>Last Name</th></tr>" ;
while($row = mysqli_fetch_array($result)){
   echo "<tr><td style=\"text-align:center;\">". $row[('CustomerID')] . "</td><td style=\"text-align:center;\">".$row[('First_name')]."</td><td style=\"text-align:center;\">".$row[('Last_name')];
  echo "</td></tr>";
  }
  echo "</table>"

Now, How can I do the same, but use the database headers in an automatically generated table? Can I also use this method to allow the user to specify the required columns in the query? Many thanks, Tommy

  • 写回答

2条回答 默认 最新

  • dsbpaqt61965 2013-07-16 19:24
    关注

    Something like this should work. You only have to define the $columns you want to display in the array map. This also works once you write the code to allow the user to select the columns she/he wants, you will only have to set this map with the selected options.

    // Define the columns title and name in this array map.
    $columns = array(
      'Customer ID' => 'CustomerID', 
      'First Name' => 'First_name',
      'Last Name' => 'Last_name'
    );
    // Run the query
    $result= mysqli_query($con,"SELECT * FROM Customers WHERE First_name = '$specFirstName'");
    
    // Output table header
    echo "<table border=\"1px solid black\" width=\"80%\"><tr>";
    foreach ($column as $name => $col_name) {
      echo "<th>$name</th>";
    }
    echo "</tr>";
    
    // Output rows 
    while($row = mysqli_fetch_array($result)) {
      echo "<tr>";
      foreach ($column as $name => $col_name) {
        echo "<td style=\"text-align:center;\">". $row[$col_name] . "</td>";
      }
      echo "</tr>";
    }
    // Close table
    echo "</table>"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂