【问题标题】:How can I create an array with all rows from database如何创建包含数据库中所有行的数组
【发布时间】:2019-11-08 03:33:48
【问题描述】:

嗨,有什么方法可以循环将我的行扔到 DB 中,如果值 Popular 为 = 1,则将其 id 分配给数组?基本上我需要循环遍历我的产品表并将所有行的 id 产品 = 1 分配给一个数组,以便稍后在我的 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();

我的数据库:

【问题讨论】:

  • 您完全忽略了从此处的结果集中实际获取任何记录,但您正试图从未在任何地方定义或分配值的变量 $row 中读取。
  • (如果您对 Popular = 1 的产品感兴趣,则应使用适当的 WHERE 子句从数据库中仅选择那些产品作为开始。 )
  • 将您的查询更改为SELECT * FROM `Products` WHERE `Popular`=1 以仅获取您想要按Popular = 1 过滤的产品

标签: php mysql


【解决方案1】:

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

SELECT ID FROM Products WHERE Popular = 1;

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

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

print_r($Popular)

【讨论】:

  • 我这样做了` $query_products = 'SELECT ID FROM Products WHERE Popular = 1;'; $result = $link->query($query_products); $Popular = mysqli_fetch_array($result); print_r($Popular);` 但是当它应该打印 id 5 和 6 时,它只打印 id 为 3 的行
  • 我的错。您需要将mysqli_fetch_array 包装在一个while 循环中,因为您必须在结果集中的每一行上调用它。我已经更新了我的答案。
【解决方案2】:

我正在使用这个 mysqli 语法,我认为它比你使用的更简单

$mysqli = new mysqli($Host, $UserName, $Password, $DataBaseName);
if (mysqli_connect_errno()) {
    printf("Connexion error : %s\n", mysqli_connect_error());
    exit();
}
$mysqli->query("SET NAMES utf8");
$query = 'SELECT  * FROM Products';
$result = $mysqli->query($query);
while ($row = $result->fetch_array()) {
     if(row['Popular']==1) { 
          //do your thing with row['ID'] 
     }
}

另外,你为什么不简单地提出请求“SELECT ID from products where Popular = 1”?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多