简体   繁体   中英

Display results from inner join with php and sql

I have the following tables with column names:

rides: id, creator, title, datetime, city, state, details
states: id, state, image
user: id, username, name, password, email, city, state

I have the following php/sql code using inner joins to get info from the tables:

$sql = "select * from ((rides inner join states on rides.state = states.id) inner join user on rides.creator = user.id) where rides.id=" . $ride;
$result = mysqli_query($dbcon, $sql);
$row = mysqli_fetch_assoc($result);

What I'm having trouble with is I want to display the state field from the states table, the username field from the user table, and all the other info from rides, but I'm unsure how to do this. I tried the following to display the state, but it didn't work:

echo $row['state']; //this displays the state field from the rides table
echo $row['states.state']; //this displays nothing

My thinking is that because the different tables have the same column names, it will take the info from the first (rides) table. Is this correct? If so, is there a way to get it to reference the different tables, or do I need to rename the columns so they have different names?

Any help is appreciated.

Select the fields you want:

select rides.*, states.state, user.username
. . .

Now, the parentheses are not needed for the joins. And table aliases make a query easier to write and to read. Finally, you should learn to use parameters. So, the query should look like this:

select r.*, s.state, u.username
from rides r inner join
     states s
     on r.state = s.id inner join
     user u
     on r.creator = u.id
where r.id = ?

The ? is a placeholder for the parameter.

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