php - 无法使用 INNER JOIN 使用 PDO 连接另一个表

标签 php mysql pdo

我正在编写一个 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/

相关文章:

php - 如何在php中将二维数组转换为一维数组?

php - Wordpress 插件安装了两次

mysql - 如何最小化sql查询

php - 使用 pdo 插入 cookie 值

php - PDO 将类获取为分组集合对象,而不是数组中的单个对象

javascript - 让 $dom = $html->load(file_get_contents($nextLink)) 等待网站加载

php - 替换字符串 PHP REGEX 中的模式

php - 选择从哪里开始而不是 substr mysql

php - MySQL 本身是否(或者如何)处理并发事务?

PHP 数据对象 (PDO) 示例