如何创建一个包含数据库中所有行的数组 [英] How can I create an array with all rows from database

查看:30
本文介绍了如何创建一个包含数据库中所有行的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi is there any way I could loop throw my rows in DB and if the value Popular is = 1 assign its id to an array? Basically I need to cycle thru my products table and assign all id of rows that product is = 1 to an array so I can use it later in my HTML. I'm using PHP7

这是我尝试实现的目标:

Here is what I tried to achieve this:

//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();

我的数据库:

推荐答案

PHP 端不用检查 Popular 的值,你可以像这样直接过滤你的行,并返回 ID 列表直接

Instead of checking the value of Popular on PHP side, you can filter directly your rows like this, and return the list of ID directly

SELECT ID FROM Products WHERE Popular = 1;

然后,您可以使用mysqli_fetch_array直接以数组的形式获取结果

Then, you can use mysqli_fetch_array to get the results as an array directly

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

print_r($Popular)

这篇关于如何创建一个包含数据库中所有行的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆