繁体   English   中英

带有内部连接的 Mysql select 语句不适用于 php,但适用于 mysql 终端

[英]Mysql select statement with inner join not working with php but works on mysql terminal

我在mysql中有三个表

表 1:项目

+----+-------------+-----------------------------+----------+---------------+
| id | ProjectName | ProjectDescription          | projType | projectStatus |
+----+-------------+-----------------------------+----------+---------------+
|  1 | RAPepsi     | Retail Audit for Pepsi      |        1 |             1 |
|  2 | RACocaco    | Retail Audit for Coke       |        1 |             1 |
+----+-------------+-----------------------------+----------+---------------+

表2:网点

id pid  poid OutletName Add1     Add2       City    Phone  interviewer Status projStat 
    1   1   11  Outlet1 Address1    Address2    City1   12345      1          1      1
    2   1   21  Outlet2 Address1    Address2    City1   12345      1          1      1
    3   2   32  Outlet2 Address1    Address2    City1   12345      3          1      1

表 3:用户

id  username        email           password
1   test1@gmail.com test1@gmail.com 123
2   test2@gmail.com test2@gmail.com 123
3   test3@gmail.com test3@gmail.com 123

我试图从分配给特定面试官的项目表中获取项目名称和描述。 我在 mysql 控制台中尝试过这段代码:

select distinct(p.ProjectName),p.ProjectDescription from outlets as oo inner join projects as p on p.id = oo.pid where oo.interviewer=(select id from users where email='test1@gmail.com');

这将根据需要获取正确的结果。 但是,当我在电子邮件是动态的 php 脚本中使用相同的代码时,它无法返回数据:

PHP脚本

include "config.php";
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
} 
$username  = (isset($_GET['userId']))?  $_GET['userId'] : 0;
$sql="select distinct(p.ProjectName),p.ProjectDescription from outlets as oo inner join projects as p on p.id = oo.pid where oo.interviewer=(select id from users where email='".$username."')";
$result = $conn->query($sql);

上面的行在 php 中不起作用 我收到以下错误:[client 103.47.158.210:56346] PHP 解析错误:语法错误,意外的“$result”(T_VARIABLE)

但是,当我使用以下代码时:它有效:

$sql = "SELECT * FROM projects where projectStatus=1 and username= '".$username."'";

当然,我使用项目表中的用户名列对此进行了测试。

我怀疑这条线是这里的问题:

$username = (isset($_GET['userId'])) ? $_GET['userId'] : 0;

这一行告诉我您正在尝试获取用户 ID(我猜是一个数字),然后在数据库中查询电子邮件(这是一个字符串)。 尝试将$username设置$username test1@gmail.com ,看看是否适合您。 如果可行,那么您知道您需要获取该用户的username而不是他们的id

另一种方法是在数据库中查询用户的id而不是他们的email 所以这将是你的新 PHP 行:

$sql="select distinct(p.ProjectName),p.ProjectDescription from outlets as oo inner join projects as p on p.id = oo.pid where oo.interviewer=(select id from users where id='".$username."')";

如果这些方法都不起作用,请仔细检查您是否连接到正确的数据库并重试。

祝你好运!

暂无
暂无

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

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