Home » Php » php – Wrong data taken from the mySQL DB using mysql_fetch_assoc

php – Wrong data taken from the mySQL DB using mysql_fetch_assoc

Posted by: admin February 25, 2020 Leave a comment

Questions:

With the below query, I’m taking data from different tables and almost all have the id field.

SELECT * FROM contracts AS co JOIN clients AS cl ON cl.id = co.client_id JOIN shops AS pv ON pv.id = co.shop_id

table structure:
contracts (id, client_id, shop_id, offer, price …)

clients (id, name, surname ..)

shops (id, code, address…)

now, using mysql_fetch_assoc, I’m printing the data in a table. All the fields are properly printed except for the id of the table contract. below the simplified PHP code:

$query = mysql_query ($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($query)){ echo $row["id"]; }

The strange thing is that the ID is printed but it is not the proper one. if I try to use “co.id” it doesn’t work at all. I know that this code is deprecated but I’m doing some update in an old project and I can’t refactor the entire project now.

The question is: is there a way to define the id that I want? I would avoid to define all the fields that i need in the SELECT replacing *.

How to&Answers:

I suggest you to mention each field in query instead of query.
field Alias can be use to prefer more suitable name, also you can skip the repeated fields, such as client_id & shop_id.

Following query will be used for the same.

SELECT 
co.id AS contract_id, co.client_id, co.shop_id, co.offer, co.price,
cl.name, cl.surname,
pv.code, pv.address
FROM contracts AS co 
JOIN clients AS cl ON cl.id = co.client_id 
JOIN shops AS pv ON pv.id = co.shop_id;

Note that, co.id will be displayed as contract_id in query result.