PDO:查找值并返回类似值的数组

时间:2014-04-07 10:33:51

标签: php mysql pdo

我的数据库中有一个表'suburb_near',其中包含列

Area,Council,Suburb,Postcode,State
Western suburbs,City of Hobsons Bay,Altona,3018,VIC
Western suburbs,City of Hobsons Bay,Altona Meadows,3028,VIC
Western suburbs,City of Hobsons Bay,Altona North,3025,VIC
Western suburbs,City of Hobsons Bay,Brooklyn (part),3012,VIC
Western suburbs,City of Hobsons Bay,Laverton,3028,VIC
Western suburbs,City of Hobsons Bay,Newport,3015,VIC
Western suburbs,City of Hobsons Bay,Spotswood,3015,VIC
Western suburbs,City of Hobsons Bay,Seabrook,3028,VIC
Western suburbs,City of Hobsons Bay,Seaholme,3018,VIC
Western suburbs,City of Hobsons Bay,South Kingsville,3015,VIC
Western suburbs,City of Hobsons Bay,Williamstown,3016,VIC
Western suburbs,City of Hobsons Bay,Williamstown North,3016,VIC

我想输入一个郊区和州,然后安理会返回该郊区。 然后我想返回位于同一个议会的所有其他郊区

<?
include("app/config/db.php");
$suburb = "Williamstown";
$state = "VIC";

$st = DBase::singleton()
        ->prepare(
            'select * ' .
            'from `suburb_near` ' .
            'where (`suburb` like :aid AND `state` like :sid)');

$st->bindParam(':aid', $suburb, PDO::PARAM_STR);
$st->bindParam(':sid', $state, PDO::PARAM_STR);

if ($st->execute())
{
       while ($row = $st->fetch(PDO::FETCH_OBJ))
        {

$council = $row->council;

}
}

echo $council;

?>

我可以回到安理会,但我不知道如何返回所有其他郊区。

1 个答案:

答案 0 :(得分:1)

假设郊区+州组合独特,

<?
include("app/config/db.php");
$suburb = "Williamstown";
$state = "VIC";

$sql = 'select t2.* from suburb_near t1 
        JOIN suburb_near t2 ON t1.council = t2.council
        where t1.suburb = ? AND t1.state = ?';
$st  = DBase::singleton()->prepare($sql);
$st->execute(array($suburb,$state));
$data = $st->fetchAll(PDO::FETCH_OBJ);
foreach($data as $row)
{
    //do whatever
}   

但是你真的需要规范化你的表结构,为所涉及的所有实体提供不同的表。