我有一个汽车库存,分为三个不同的表,每辆车在所有三个表上都有相同的aut_id
。
我试图遍历每辆车的汽车while ($counter <= $autocount)
含义,并从每张汽车的三个表中获取信息,以显示mileage
和price
这是我到目前为止的代码
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
}
答案 0 :(得分: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
答案 1 :(得分: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
}
与您的查询不同,这些实际上是prepared并且稍后会绑定。这可以防止sql注入。
检查代码上的注释,以确切了解所有内容的含义。