简体   繁体   中英

Left join with empty table makes the column that is joined on null in php, but works normally in phpmyadmin

I have a users and a userfollowers table. They both have a user_id column.

The userfollowers table might be empty or does not have a match yet for a user in the users table, hence why i use a left join .

This is my query:

SELECT * 
FROM users 
LEFT JOIN userfollowers ON users.user_id = userfollowers.user_id 
WHERE user_name = ?"

When I try to execute this query in my php prepared statement, it returns all columns correctly, except the user_id from the users table is suddenly NULL.

When I try this query in phpmyadmin, it returns all columns including the user_id from the users table as intended.

Can someone tell me what is going on?

In PHP only 1 indice can exist in an array so the latter column, userfollowers.user_id overwrites the first value users.user_id . You need to list the columns, use aliases for all columns, or use numeric indices (which will be difficult to determine which value is which).

You could do something like this if all columns from users should be returned:

SELECT u.*, uf.somecolumn
FROM users as u
LEFT JOIN userfollowers as uf using(user_id) 
WHERE user_name = ?

The as u is a table alias, that allows you to use the shorter syntax when referencing the table. Tha same can be done for columns. With original query if you needed both user_id s could do:

SELECT u.user_id as users_id, uf.user_id as userfollowers_userid 
FROM users as u
LEFT JOIN userfollowers as uf using(user_id)
WHERE user_name = ?

then PHP would have both $row['userfollowers_userid'] and $row['users_id'] available.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM