【发布时间】:2019-08-13 15:35:39
【问题描述】:
我正在使用SELECT * FROM products WHERE id IN ('$arrayImplodedToStr') SQL 查询同时从数据库中获取多个值。查询工作正常,因为当我回显$q 时,我可以看到所有数组项都转换为查询中的 id 号,并且其中有很多。但是当我进行查询并将其存储在数组中,然后在while 循环中使用mysqli_fetch_assoc() 从查询中获取所有行时,我总是只得到一个和第一个项目。不知道为什么?
代码:
session_start();
require_once('navigation.php');
require_once('database_connection.php');
if(empty($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
array_push($_SESSION['cart'], $_GET['product_id']);
$arrayImplodedToStr = implode(',', $_SESSION['cart']);
$q = "SELECT * FROM products WHERE id IN ('$arrayImplodedToStr')";
$result = mysqli_query($dbc, $q);
mysqli_query($dbc, $q);
$allRows = [];
while($row = mysqli_fetch_assoc($result)) {
$allRows[] = $row;
}
foreach ($allRows as $cartItems) {
echo $cartItems['name'];
}
【问题讨论】:
-
您的查询将类似于
"SELECT * FROM products WHERE id IN ('1,2,3,4,5')",这是不正确的。您需要在 implode 中添加单引号。
标签: php mysql sql loops mysqli