我有一个特殊的问题。我试图使用 for循环将表产品中的行(共有5条)放入php数组( $ ro )中。我的代码成功完成了前2个循环,并确认数组中有5行。但是,放入数组的第二行实际上是表中的第三行,就像我说的那样,在第二个循环之后,我的函数停止获取行。
我测试了打印数组和ID并得到以下结果:
1=>Array ( [sku] => JVC200123 [name] => Acme DISC [price] => 1.00 [type] => disc [value] => 700 )
2=>Array ( [sku] => GGWP0008 [name] => Preacher [price] => 24.99 [type] => book [value] => 1 )
...345
我想念什么?这是有问题的代码:
protected function get_prod($conn1)
{
$pluck_type = array();
$objects = array();
$call_type = 'SELECT id, type FROM products ORDER BY id';
$type_res = mysqli_query($conn1, $call_type);
$index = 0;
while($row = mysqli_fetch_assoc($type_res)){
$pluck_type[$index] = $row;
$index++;
}
for ($roww = 0; $roww < count($pluck_type); $roww++) {
$product_type = $pluck_type[$roww]['type'];
$rowid = $pluck_type[$roww]['id'];
if($product_type == 'disc')
{
$sql = "SELECT p.sku, p.name, p.price, p.type, a.value FROM products AS p INNER JOIN attr_size AS a ON p.id = a.product_id WHERE a.id = '".$rowid."';";
echo $rowid;
}
else if ($product_type == 'book')
{
$sql = "SELECT p.sku, p.name, p.price, p.type, a.value FROM products AS p INNER JOIN attr_weight AS a ON p.id = a.product_id WHERE a.id = '".$rowid."';";
echo $rowid;
}
else if ($product_type == 'furniture')
{
$sql = "SELECT p.sku, p.name, p.price, p.type, CONCAT(a.height, 'x', a.width, 'x', a.length) AS value FROM products AS p INNER JOIN attr_dims AS a ON p.id = a.product_id WHERE a.id = '".$rowid."';";
echo $rowid;
}
$val_res = mysqli_query($conn1, $sql);
$ro = mysqli_fetch_assoc($val_res);
print_r($ro);
$objects[$roww] = $ro;
}
$this->objekt = $objects;
}
答案 0 :(得分:2)
您正在测试WHERE
子句中的错误列。
WHERE a.id = '".$rowid."';";
应该是
WHERE a.product_id = '".$rowid."';";
或
WHERE p.id = '".$rowid."';";
您可以将所有操作作为一个查询来完成:
SELECT *
FROM (
SELECT p.id, p.sku, p.name, p.price, p.type, a.value
FROM products AS p
INNER JOIN attr_size AS a ON p.id = a.product_id
WHERE p.type = 'disc'
UNION ALL
SELECT p.id, p.sku, p.name, p.price, p.type, a.value
FROM products AS p
INNER JOIN attr_weight AS a ON p.id = a.product_id
WHERE p.type = 'book'
UNION ALL
SELECT p.id, p.sku, p.name, p.price, p.type, CONCAT(a.height, 'x', a.width, 'x', a.length) AS value
FROM products AS p
INNER JOIN attr_dims AS a ON p.id = a.product_id
WHERE p.type = 'furniture'
) AS x
ORDER BY x.id