首页 > 解决方案 > 如何创建包含数据库中所有行的数组

问题描述

嗨,有什么方法可以循环将我的行扔到 DB 中,如果值 Popular 为 = 1,则将其 id 分配给数组?基本上我需要循环遍历我的产品表并将产品为 = 1 的所有行的 id 分配给一个数组,以便稍后在我的 HTML 中使用它。我正在使用 PHP7

这是我试图实现的目标:

//Variables
  $Host = 'localhost';
  $UserName = 'root';
  $Password = 'NOP';
  $DataBaseName = 'BoosTemplatesDB';
  $DEBUG = True;

  $link = mysqli_connect($Host, $UserName, $Password, $DataBaseName);

  // If the script cant connect to DB it will redirect to 409 error page and exit.
  if (mysqli_connect_error()) {
    if ($DEBUG == True) {
      die ('MySQL error trying to connect to host '.mysqli_connect_error());
    } else {
      header("Location: http://127.0.0.1/409.html");
      exit();
    }
  }

  $query_products = 'SELECT * FROM Products';
  $result = $link->query($query_products);

  if ($result->num_rows > 0) {

    $Popular = array();

    while($row != 4) {
        if ($row['Popular'] == 1) {
          $value = $row['ID'];
          array_push($Popular,$value);
        }
    }
    echo $value;
  } else {
    if ($DEBUG == True) {
      die ('MySQL couldnt find any result for the query: '.$query_products);
    } else {
      header("Location: http://127.0.0.1/409.html");
      exit();
    }
  }

$link->close();

我的数据库: 在此处输入图像描述

标签: phpmysql

解决方案


无需检查PopularPHP 端的值,您可以像这样直接过滤行,并直接返回 ID 列表

SELECT ID FROM Products WHERE Popular = 1;

然后,您可以使用mysqli_fetch_array直接将结果作为数组获取

while ($row = mysqli_fetch_array($result)) {
  $Popular[] = $row;
}

print_r($Popular)

推荐阅读