【发布时间】: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 过滤的产品