[英]JOIN table MySQL not joining in PHP
I am trying to learn how to use JOIN
, INNER JOIN
, LEFT JOIN
and RIGHT JOIN
. 我正在尝试学习如何使用
JOIN
, INNER JOIN
, LEFT JOIN
和RIGHT JOIN
。 I have the following users and generator tables 我有以下用户和生成器表
users
uid
username
password
email
and 和
creator
id
uid
g_name
g_bio
But I cannot join them. 但是我不能加入他们。 I try to
JOIN
like this : 我尝试这样
JOIN
:
public function Generator($uid) {
$g_name=mysql_real_escape_string($uid);
$query= mysql_query ("SELECT username,g_name,g_bio FROM users JOIN creator ON users.uid = creator.uid");
$data=mysql_fetch_array($query);
return $data;
}
But print_r
does not show anything? 但是
print_r
什么都不显示? What is wrong here? 怎么了
First thing, when you are referencing two tables, you need to specify from which table you are selecting each column from: 首先,当您引用两个表时,需要指定从哪个表中选择每一列:
SELECT
users.username,
creator.g_name,
creator.g_bio
FROM users
JOIN creator ON users.uid = creator.uid
Second, in your function, you are passing in $uid
, and then converting it to $g_name
, but not using it anywhere in your query. 其次,在函数中,您传入
$uid
,然后将其转换为$g_name
,但不在查询中的任何地方使用它。 Assuming you want rows matching this value, you need to add an additional where
condition: 假设要使行与该值匹配,则需要添加其他
where
条件:
WHERE creator.g_name = '$g_name'
Finally, don't use the mysql_*()
functions , instead use mysqli or pdo and utilize prepared statements. 最后, 不要使用
mysql_*()
函数 ,而要使用mysqli或pdo并利用准备好的语句。
You escaped function argument $uid to $g_name but you don't use it. 您将函数参数$ uid转义为$ g_name,但未使用它。 May be it the reason of "nothing happened" ?
可能是“什么都没发生”的原因吗? You should rewrite your query that way :
您应该这样重写查询:
"SELECT username,g_name,g_bio FROM users
JOIN creator ON users.uid = creator.uid
WHERE g_name = '$g_name'"
Beyond that I think you better should use PDO and a parameterized queries 除此之外,我认为您最好使用PDO和参数化查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.