简体   繁体   English

使用 php 和 sql 显示内连接的结果

[英]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:我有以下 php/sql 代码使用内部联接从表中获取信息:

$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.我的想法是,因为不同的表具有相同的列名,所以它会从第一个 (rides) 表中获取信息。 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.是参数的占位符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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