使用其他表php的列表从一个表中获取数据

时间:2013-03-18 08:22:25

标签: php pdo

我有以下表格

myListTable

playerId listId type
 50       10     0
 51       10     0

玩家

id  x  xx etc
50  x  xx etc
51  x  xx etc

我想运行一个查询,我提供listId和type,它将获得与该listId相关的所有玩家的列表并输入

try {
    $conn = $this->GetDBConnection();
    $type = 0; // 0 REQUEST BY PLAYERS
    $statement = $conn->prepare('SELECT p.* FROM myListTable c, players p WHERE (c.listId = :listId ) AND (c.type = :type) AND ( p.id = c.playerId) ');
    $statement->bindParam(':listId', $listId, PDO::PARAM_INT);
    $statement->bindParam(':type', $type, PDO::PARAM_INT);
    $statement->execute();
    if(!($row = $statement->fetchAll(PDO::FETCH_ASSOC))) {
        return false;
    }
    $conn = null;
} catch(PDOException $e) {
    throw $e;
}

这只是让我虚假。我该怎么做才能修复此查询?

1 个答案:

答案 0 :(得分:4)

其中一个错误是准备查询中的拼写错误:

$statement = $conn->prepare('SELECT p.* 
    FROM myListTable c, players p 
    WHERE (c.listId = :c.listId ) 
        AND (c.type = :type) 
        AND ( p.id = c.playerId) ');

:c.listId应为:listId

第二个是,type是MySQL中的保留字。你需要反引号才能在查询中转义它。

另一个是,因为你只是从players表中选择值;首选JOIN

查询应为:

SELECT p.*
FROM players p
JOIN myListTable c
    ON (p.id = c.playerId)
WHERE (c.listId = :c.listId)
    AND (c.`type` = :type)