php - 如何创建包含数据库中所有行的数组
问题描述
嗨,有什么方法可以循环将我的行扔到 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();
解决方案
无需检查Popular
PHP 端的值,您可以像这样直接过滤行,并直接返回 ID 列表
SELECT ID FROM Products WHERE Popular = 1;
然后,您可以使用mysqli_fetch_array
直接将结果作为数组获取
while ($row = mysqli_fetch_array($result)) {
$Popular[] = $row;
}
print_r($Popular)
推荐阅读
- vba - 如何查看 ComboBox 是否处于 DropDown 状态?
- python - 循环遍历多个 json 输入文件
- javascript - 反应:从 cookie 加载组件状态时未更新组件状态
- rest - 在 RESTful API 中管理 m:n 关系的最佳实践
- typescript - 为什么以下 rxjs 调用 switchMap 会出现类型错误?
- excel - 适合初学者的简单 v 查找
- c++ - 在用户输入值而不覆盖以前的值后,如何写入 .csv 文件的下一行?
- assembly - 如何实现将所有寄存器推送到堆栈的循环
- java - 静态字符串怪异行为 Diamond Star Pattern 问题
- c# - Microsoft azure service bus api - How to add AutoDeleteOnIdle on subscription description