i need to get the latest order (from our custon admin panel). here’s my query:
select *
from order
left join customer
on (customer.id = order.fk_cid)
where date = curdate()
order by time desc
limit 1;
this output everything from orders and customers which i need except 1 therefore that is why i use the *
here’s my table structure:
order table:
id, fk_cid, date, time
customer table:
id, name, lastname, street, city, zip, country, phone, email, lastlogin
now, in my php i have:
$result = mysql_query("
select *
from `order`
left join customer
on (customer.id = order.fk_cid)
where date = curdate()
order by time desc
limit 1");
$row = mysql_fetch_assoc($result, MYSQL_ASSOC);
at this point my order is not correct, why?
Your
customers.idis overwriting theorder.idbecause you are using the same column name.As you can see in this example you have two
id, so PHP when retrieve the data usingmysql_fetch_associt overwrites the secondidbecause it’s the same key in the array. To fix this, you will have to specify the columns in your query:This will output:
Also, I recommend to use different name for your tables and fields.
order,date,timesince they are reserved word (in case you forget for use the ` ).Also here’s a topic you should read: Why is SELECT * considered harmful?