-3

我有一个汽车库存,分为三个不同的桌子,每辆车aut_id在所有三个桌子上都相同。

我试图遍历每辆车的while ($counter <= $autocount)意义,并从每辆车的三个表中获取信息以显示数据,例如mileageprice

到目前为止,这是我的代码

while ($counter <= $autocount)  //ie run for every car 
{
    $sql = "SELECT * FROM `auto` WHERE `auto_id` > $auto_id AND 
    `sold` = $soldvalue";
    $get = $dbh->prepare($sql);
    $get->execute();

    $sql1 = "SELECT * FROM `attributes` WHERE `auto_id` > $auto_id AND 
    `sold` = $soldvalue";
    $get1 = $dbh->prepare($sql1);
    $get1->execute();

    $sql2 = "SELECT * FROM `pictures` WHERE `auto_id` > $auto_id AND 
    `sold` = $soldvalue";
    $get2 = $dbh->prepare($sql2);
    $get2->execute();

    $attributes = 
    $auto =
    $pictures = 

@RichardA 我的最终解决方案

// Get all the cars, join their attributes and pictures according to
// the `auto_id`
$query = "SELECT * FROM `auto`
INNER JOIN `attributes` ON `auto`.`auto_id` = `attributes`.`auto_id`
INNER JOIN `pictures` ON `auto`.`auto_id` = `pictures`.`auto_id`
WHERE `auto`.`soldvalue` = :soldvalue AND `auto`.`autoid` > :autoid";

// Prepare the query, binding parameters to prevent SQL injections
$getAutos = $dbh->prepare($query);

// Bind the autoid
$getAutos->bindParam(":autoid", $auto_id, PDO::PARAM_INT);

// Bind the soldvalue
$getAutos->bindParam(":soldvalue", $soldvalue, PDO::PARAM_INT);

// Execute the query
$getAutos->execute();

// Fetch all the cars now, only getting an ASSOCIATIVE ARRAY
$autos = $getAutos->fetchAll(PDO::FETCH_ASSOC);

// Loop through each car
foreach($autos as $auto)
{
    // Display the cars here
}
4

2 回答 2

0

这可以在单个查询中完成,尝试这样的事情:

// Get all the cars, join their attributes and pictures according to
// the `auto_id`
$query = "SELECT * FROM `auto`
INNER JOIN `attributes` ON `auto`.`auto_id` = `attributes`.`auto_id`
INNER JOIN `pictures` ON `auto`.`auto_id` = `pictures`.`auto_id`
WHERE `auto`.`soldvalue` = :soldvalue AND `auto`.`autoid` > :autoid";

// Prepare the query, binding parameters to prevent SQL injections
$getAutos = $dbh->prepare($query);

// Bind the autoid
$getAutos->bindParam(":autoid", $auto_id, PDO::PARAM_INT);

// Bind the soldvalue
$getAutos->bindParam(":soldvalue", $soldvalue, PDO::PARAM_INT);

// Execute the query
$getAutos->execute();

// Fetch all the cars now, only getting an ASSOCIATIVE ARRAY
$autos = $getAutos->fetchAll(PDO::FETCH_ASSOC);

// Loop through each car
foreach($autos as $auto)
{
    // Display the cars here
}

与您的查询不同,这些实际上是稍后准备和绑定的。这可以防止 sql 注入。

检查代码上的注释以确切了解所有内容背后的含义。

于 2013-08-16T07:13:21.337 回答
0

您必须通过获取它们来获取所有结果并将它们存储在变量中

$attributes = $get->fetch(PDO::FETCH_ASSOC);
$auto       = $get1->fetch(PDO::FETCH_ASSOC);
$pictures   = $get2->fetch(PDO::FETCH_ASSOC);

因此

$attribute[keyname / index name / column name] = value
$auto[keyname / index name / column name]      = value
$pictures[keyname / index name / column name] = value
于 2013-08-16T06:52:35.387 回答