SQL表比较,构建查询并将过滤后的数据打印到下拉列表中

时间:2013-11-13 20:05:55

标签: php sql mysqli

我有一个名为user_id的表的存储值。我有另一张桌子:

client_projects:

+------------------+-------------+-------------+-------------+
| project_codename | client_id_1 | client_id_2 | client_id_3 |
+------------------+-------------+-------------+-------------+
|       Alpha      |      1      |      2      |      3      |
+------------------+-------------+-------------+-------------+
|       Beta       |      2      |      1      |      0      |
+------------------+-------------+-------------+-------------+
|       Gamma      |      3      |      1      |      0      |
+------------------+-------------+-------------+-------------+

如果user_id =(client_id_1或client_id_2或client_id_3),那么我想在下拉列表中打印相应的project_codenames。这是我的PHP但没有返回正确的结果。我推销了我不确定的领域。

PHP(已更新并已解决):

<?php

  $con = mysqli_connect("localhost","****","****","db") or die("Connection error: " . mysqli_error($con));

  //stored sample value from another table 
  $user_id = "1";

  //Build query: Not sure if this is correct format
  $query = "SELECT * FROM client_projects WHERE client_id_1 = $user_id OR client_id_2 = $user_id OR client_id_3 = $user_id";
  $result = mysqli_query($con, $query) or die("Query error: " . mysqli_error($con));

  //Drop down list
  echo '<select id="Projects" class="input">';
  echo '<option value="" selected="selected" disabled="disabled">Choose a Project...</option>';

  // Loop through the query results, outputing specific options one by one
  // Not sure of the loop for the options
  while ($row = mysqli_fetch_array($query)) {
    echo '<option value="'.$row['project_codename'].'">'.$row['project_codename'].'</option>';
  }
  echo '</select>';

  mysqli_close($con);
?>

1 个答案:

答案 0 :(得分:0)

您将$ query直接输入mysqli_fetch_array(),但此函数需要将结果资源作为输入。你错过了mysqli_query()调用。请参阅manual page

上的示例#2