Mysqli从两个不同的表中获取信息

时间:2022-03-16 15:42:07

I have two different tables one hold comments and the other user information my first mysqli_prepare statement looks like this

我有两个不同的表一个保存注释,另一个用户信息我的第一个mysqli_prepare语句是这样的。

    if($stmt = mysqli_prepare($mysqli, "SELECT text,username,id,likes,dislikes FROM post WHERE school = '$sname' ORDER BY id DESC LIMIT 0,10"))

and the other looks like this

另一个像这样

   if($stmts = mysqli_prepare($mysqli, "SELECT avatar FROM users WHERE username = '$user'"))

basically i need to combine these two statements so that I can access both sets in the same while loop which looks like this

基本上,我需要合并这两个语句这样我就可以在相同的while循环中访问这两个集合,就像这样

    while(mysqli_stmt_fetch($stmt))

any help is appreciated thank you in advance and I will vote up.

感谢您的帮助,我将会投票。

2 个解决方案

#1


2  

JOIN operation on common field username

在公共字段用户名上加入操作

SELECT post.text,post.username,post.id,post.likes,post.dislikes FROM post 
INNER JOIN users 
ON post.username = users.username
WHERE post.school = '$sname' 
AND users.username = '$user'
ORDER BY post.id DESC LIMIT 0,10

#2


1  

To do so with SQL you will need to combine your queries using JOIN.

要使用SQL实现这一点,您需要使用JOIN来组合查询。

Making some assumptions, the following is an example:

做一些假设,下面是一个例子:

SELECT ... FROM post JOIN users ON post.username = users.username WHERE ...

Note: An alternative would be to SELECT the data separate (as you have) and stitch the data together with PHP. Sometimes this is preferred over a complex JOIN. However, what you have seems fine.

注意:另一种选择是选择单独的数据(正如您所做的),并将数据与PHP结合在一起。有时这比复杂连接更可取。然而,你所拥有的似乎还不错。

#1


2  

JOIN operation on common field username

在公共字段用户名上加入操作

SELECT post.text,post.username,post.id,post.likes,post.dislikes FROM post 
INNER JOIN users 
ON post.username = users.username
WHERE post.school = '$sname' 
AND users.username = '$user'
ORDER BY post.id DESC LIMIT 0,10

#2


1  

To do so with SQL you will need to combine your queries using JOIN.

要使用SQL实现这一点,您需要使用JOIN来组合查询。

Making some assumptions, the following is an example:

做一些假设,下面是一个例子:

SELECT ... FROM post JOIN users ON post.username = users.username WHERE ...

Note: An alternative would be to SELECT the data separate (as you have) and stitch the data together with PHP. Sometimes this is preferred over a complex JOIN. However, what you have seems fine.

注意:另一种选择是选择单独的数据(正如您所做的),并将数据与PHP结合在一起。有时这比复杂连接更可取。然而,你所拥有的似乎还不错。