您好,有什么方法可以循环将行扔到DB中,如果值Popular = 1,则将其ID分配给数组?基本上,我需要循环遍历product表,并将product = 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();
答案 0 :(得分:2)
您可以像这样直接过滤行,而不用检查PHP端Popular
的值,并直接返回ID列表
SELECT ID FROM Products WHERE Popular = 1;
然后,您可以使用mysqli_fetch_array
直接将结果作为数组获取
while ($row = mysqli_fetch_array($result)) {
$Popular[] = $row;
}
print_r($Popular)
答案 1 :(得分:0)
我正在使用这种mysqli语法,我认为它比使用您的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']
}
}
此外,为什么不简单地发出“从Popular = 1的产品中选择SELECT ID”的请求?