So, I have a database table called customers. The last 6 products they have purchased is stored in the customer table under "p1, p2, p3, p4, p5 and p6". The product would then be stored as the product number, eg
Last Purchased:
p1: 12355
p2: 55142
p3: 51251
etc. These products all have they're own table row in the "Products" table. On that list is amongst others "price". Now, what I would like to do is an somewhat easy way to extract the biggest purchase amongst the last 6 purchases. Getting the biggest is easy by using the max()
command, and I could do something like the whole
$p1 = $array[0]["p1"];
$array = $db->queryA("SELECT * FROM products WHERE product = $p1");
and then compare them as in max($p1,$p2,$p3) etc. My problem is this would take an enormous amount of time and code. Is there a better way of doing this, for instance with an foreach loop? I am really sorry, but I am completely stomped. Again.. All help is appreciated. :)
Edit: not sure how to display the table structure, but here goes my attempt, sorry if it is bad :(
customers products
id prod_nr
name name
mail price
member_since quantity
p1
p2
p3
p4
p5
p6
Would this suffice? It is some more fields, but it is the gist of it. Also, "id" and "prod_nr" are primaries
edit nr2: also wanted to explain that I have about 11 of these 6* queries I would like to run, so as to not making you think I'm just wasting your time instead of a little of mine... :)
Edit again, here is the part of the database provider giving me problems...
public function query($query)
{
try{
$query = trim($query);
$sth = $this->pdo->query($query,PDO::FETCH_ASSOC);
$result = null;
foreach($sth as $row) {
$result[] = $row;
}
return $result != null ? json_encode($result) : null;
}
catch(exception $e)
{
echo('Exception ' . $e);
}
}
What you could do is all the items to an array, and then implode it so it uses single quotes and then execute a query like this:
$array = $db->queryA("SELECT * FROM products WHERE product IN($your_array)");
First you need is redesign your database you need a purchase table like this
purchase
---------
id_purchase
id_customer
id_product
customers
-----------
id
name
mail
member_since
products
------------
prod_nr
name
price
quantity
Then your SQL would be:
SELECT * from customers JOIN purchase ON id = id_customer JOIN products ON prod_nr = id_product
ORDER BY DESC price
LIMIT 1