Php 如何使用数据库中的所有行创建数组
嗨,我有没有办法在DB中循环抛出我的行,如果值Popular=1,将其id分配给数组?基本上,我需要循环遍历我的products表,并将product=1的所有行id分配给一个数组,以便稍后在HTML中使用它。 我用的是PHP7 以下是我试图实现的目标:Php 如何使用数据库中的所有行创建数组,php,mysql,Php,Mysql,嗨,我有没有办法在DB中循环抛出我的行,如果值Popular=1,将其id分配给数组?基本上,我需要循环遍历我的products表,并将product=1的所有行id分配给一个数组,以便稍后在HTML中使用它。 我用的是PHP7 以下是我试图实现的目标: //Variables $Host = 'localhost'; $UserName = 'root'; $Password = 'NOP'; $DataBaseName = 'BoosTemplatesDB'; $DEBU
//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();
我的数据库:
您可以像这样直接过滤行,直接返回ID列表,而不是在PHP端检查Popular的值
SELECT ID FROM Products WHERE Popular = 1;
然后,您可以使用直接作为数组获取结果
while ($row = mysqli_fetch_array($result)) {
$Popular[] = $row;
}
print_r($Popular)
我正在使用这个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的产品中选择ID 您完全忽略了从这里的结果集中实际获取任何记录,但您正在尝试从未在任何地方定义或分配值的变量$row中读取。如果您只对Popular=1的产品感兴趣,则应首先从数据库中选择这些产品,通过使用适当的WHERE子句。将查询更改为从'Products'中选择*,其中'POWERIC`=1,以仅获取要按POWERIC=1筛选的产品。我执行了以下操作:“$query\U Products='从POWERIC=1的产品中选择ID;”$结果=$link->query$query\u产品$Popular=mysqli\u fetch\u array$result;打印\u r$Popular;`但它只打印id为3的行,而应该打印id为5和6My的行。您需要将mysqli_fetch_数组包装在while循环中,因为您必须在结果集中的每一行上调用它。我已经更新了我的答案。