PDO子查询在循环内使用变量

时间:2014-07-08 04:44:10

标签: php mysql pdo subquery

我正在尝试使用动态变量在While循环中编写查询,但似乎无法使其正常工作。我是PDO的新手,所以如果这甚至是正确的方法,我也不是100%。与数据库的连接($ db)工作正常,查询运行正常,没有第二个$ STH2行。请帮助:)

<?php

//This will list player info so the user can get the correct player  ID
$STH = $db->query('SELECT id, name, tag from wdlTeams');

//Setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);

//Create listbox object and populates options with team names 
echo "<select name='teamID'>";
while($row = $STH->fetch()) {
    $id = $row['id'];
    $name = $row['name'];
    $tag = $row['tag'];
    $seasonId = $row['seasonId'];

    $STH2 = $db->prepare('SELECT name from wdlSeasons where id=$seasonId');
    $STH2->execute();
    $seasonName = $STH2->fetchColumn();

    echo "<option value='$id'>$tag - $name ($seasonName)</option>";
    echo "<br />";
}
echo "</select>";

?>  

我也尝试过改为

 $STH2 = $db->prepare("SELECT 'name' from 'wdlSeasons' where id='$seasonId'");

但没有运气

1 个答案:

答案 0 :(得分:0)

试试这个:

$STH2 = $db->prepare('SELECT name from wdlSeasons where id=:id'); $STH2->bindParam(':id', $seasonId); $STH2->execute();