Php pdo JOIN request result
My problem
I am trying to do a simple JOIN between two tables, both have an id field. My result is a stdClass object as I am using PDO. Does anyone know how I can change the difference between the ID of the first table and the ID of the second table?
code
$sql = "SELECT * FROM products AS p
products_categories AS c
WHERE c.id = p.category";
$stmt = $connection->prepare($sql);
$stmt->execute();
$products = array();
while($product = $stmt->fetchObject())
$products[] = $product;
return $products;
If I try to use $ products-> id it shows me the id of the category table. If it were an array I could use $ products ['p.id'], I need an alternative to this.
Many thanks.
source to share
You must specify a column alias in a column id
from one table or another to make the column names different.
This means that you cannot use " SELECT *
", you must supply all the column names that you want to retrieve from this table. At the very least, you can still query category.*
if you want all those columns without anti-aliasing.
By the way, this problem is a good reason to avoid using a common name like " id
" for your primary key in every table. Use more descriptive names like product_id
and instead category_id
. Then you will have no problem with conflicting column names.
source to share
$ stmt = $ db-> prepare ("SELECT c.car_id, c.car_name, d.dealers_name, m.maker_name FROM car_details AS c, dealer_details AS d, maker_details AS m WHERE c.dealer_id = d.dealer_id AND c.maker_id = m.maker_id ");
$ stmt-> Execute (); $ rows = $ stmt-> fetchAll (PDO :: FETCH_ASSOC);
echo ''; print_r ($ strings);
source to share