我正在编写一个 PHP 脚本,并且想要创建一个 INNER JOIN,这样我就可以 SELECT
来自另一个表的数据,其中 id
(在 theList
表中)和 postid
(在 post_rating
)表是相同的。
我相信代码应该如下所示:
INNER JOIN post_rating ON theList.id=post_rating.postid
下面是我正在使用的代码。我添加了$join
变量。
由于某种原因它不起作用!当我尝试删除 $join 并只有 post_rating.postid
时在 SELECT
它也不起作用 - 如果有帮助的话!
我怎样才能让它工作!非常感谢:)
<?php
$pdo = new PDO('mysql:host=localhost;dbname=myDB', 'root', 'root');
$select = 'SELECT theList.id, theList.name, post_rating.postid';
$from = ' FROM theList';
$where = ' WHERE TRUE';
$join = ' INNER JOIN post_rating ON theList.id=post_rating.postid';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("pub", $opts)){
$where .= " AND pub = 1";
}
if (in_array("bar", $opts)){
$where .= " AND bar = 1";
}
if (in_array("restaurant", $opts)){
$where .= " AND restaurant = 1";
}
if (in_array("club", $opts)){
$where .= " AND club = 1";
}
$sql = $select . $from . $where . $join ;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
最佳答案
有效查询中 JOIN 之后的位置,因此将位的串联修改为 $sql
$sql = $select . $from . $join . $where;
关于php - 无法使用 INNER JOIN 使用 PDO 连接另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52630803/