Reputation: 25
I have a peculiar problem. I am trying to put rows (which there are 5) from my table products into a php array ($ro), using a for loop. My code succeeds in doing this for the first 2 loops, and acknowledges that there are 5 rows to put in the array. However, the second row that gets put in my array is actually the third row in my table, and like I said, after the second loop, my function stops getting rows.
I tested printing my arrays and id's and got the following:
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
What am I missing? Here is the code in question:
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;
}
Upvotes: 1
Views: 47
Reputation: 781058
You're testing the wrong column in your WHERE
clauses.
WHERE a.id = '".$rowid."';";
should be
WHERE a.product_id = '".$rowid."';";
or
WHERE p.id = '".$rowid."';";
You could do this all as one query:
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
Upvotes: 2