r/PHPhelp • u/mratin • Oct 04 '25
help with a query (mysql, php)
Hey, I'm currently in the process of creating a an e-shop and I ran into a little problem. I'm sure the solution is trivial, but for the life of me I can't seem to get anything to work. I also wish to only do one single query to the db.
So I have table 'products' with a bunch of attributes, PK being 'product_id'. In it there is a column for 'price'. I'd like to extract all rows of this column into an array that I can easily use. I.e. $priceArray[0] would correspond to the price of product_id=1.
Is there an elegant solution to this without indeed doing several queries with WHERE statements?
Thank You
4
u/ZeFlawLP Oct 04 '25
SELECT price FROM products?
2
u/swampopus Oct 05 '25
I promise I'm not trying to be a jerk or gatekeeper, but if you are at a level where you don't know how to execute a query and get the results into an array, I don't think you're ready to program an ecommerce shop.
Or is this just like a homework assignment?
1
u/kwong63 Oct 04 '25
you have an id (your PK). why not use that as the key for an associative array?
you end with a “map” like [1 => {price of product_id=1}]
better than using indexed array imo unless you have some very specific need for an indexed array
1
u/colshrapnel Oct 05 '25
This idea is quite wrong. There is no way to tell which price belongs to whic product or even guarantee that the order will be the same.
it must be $priceArray[1] or whatever product_id the first product has.
So your code must be like
-1
u/isoAntti Oct 04 '25
Some kind of database abstraction layer is nice in these situations. I like for example PEAR::DB . You get with one getAssoc a nice array of results. Others like to use exceptions.