Loop内的Multiples查询并非全部工作

时间:2013-06-16 18:07:38

标签: php loops

我尝试优化我拥有的脚本,以便加载更快。 现在我已经在这里待了好几个小时但是没有让它正常工作。

第一部分工作正常,但不起作用的是获取sire_id($ sr查询)和dam_id(($ dr查询)的名称 它显示为结果"数组"对所有人来说。

这是我到目前为止所写的内容

$query = "SELECT COUNT(sire_id) as c, sire_id FROM dog WHERE sire_id IS NOT NULL GROUP BY sire_id ORDER BY c desc LIMIT 150"; 
$result = mysql_query($query) ;
$i=0;
while ($line = mysql_fetch_array($result)) {
    $sireQuery = "SELECT name, id, sire_id, dam_id FROM dog WHERE id = '$line[sire_id] '";
    $sireResult = mysql_query($sireQuery) ;
    $sireLine = mysql_fetch_array($sireResult);
    $sr = mysql_query("SELECT name FROM dog WHERE id like $sireLine[2]") ;
    $sl = mysql_fetch_array($sr);       
    $dr = mysql_query("SELECT name FROM dog WHERE id like $sireLine[3]") ;
    $dl = mysql_fetch_array($sr);                       
    $i++;

    echo "</td><td>".$i. '&nbsp;', '&nbsp;', '&nbsp;',"<a href='details.php?id=".$line[1]."'>"  .$sireLine[0]. "</td>
          <td>".$line[0]." </td>
          <td>".$sl." </td>
          <td>".$dl." </td></tr>";      
}

2 个答案:

答案 0 :(得分:0)

根据定义,ID是数字,您不需要使用引号。此外,您添加了一个不必要的空间:

$sireQuery = "SELECT name, id, sire_id, dam_id FROM dog WHERE id = " . $line["sire_id"];

此外,以下行可能需要调整(等待您对id列的数据类型的回答)

$sr = mysql_query("SELECT name FROM dog WHERE id = " . $sireLine["sire_id"]);
$sl = mysql_fetch_array($sr);
$dr = mysql_query("SELECT name FROM dog WHERE id = " . $sireLine["dam_id"]);
$dl = mysql_fetch_array($dr);   /* note the mistake in the variable name: this is $dr, not $sr */

...

<td>" . $sl["name"] ." </td>
<td>" . $dl["name"] ." </td></tr>";

答案 1 :(得分:0)

我重写了你的例子:

$query = "SELECT COUNT(sire_id) as c, sire_id FROM dog WHERE sire_id IS NOT NULL GROUP BY sire_id ORDER BY c desc LIMIT 150";
$result = mysql_query($query) ;
$i=0;

while ($line = mysql_fetch_assoc($result)) {
    $sireQuery = "SELECT name, id, sire_id, dam_id FROM dog WHERE id = {$line['sire_id']}";
    $sireResult = mysql_query($sireQuery) ;
    $sireLine = mysql_fetch_assoc($sireResult);
    $sr = mysql_query("SELECT name FROM dog WHERE id = {$sireLine['sire_id']}") ;
    $sl = mysql_fetch_assoc($sr);
    $dr = mysql_query("SELECT name FROM dog WHERE id = {$sireLine['sire_id']}") ;
    $dl = mysql_fetch_assoc($sr);
    $i++;

    echo "</td><td>".$i. '&nbsp;', '&nbsp;', '&nbsp;',"<a href='details.php?id=".$line[1]."'>"  .$sireLine[0]. "</td>
          <td>{$line['c']} </td>
          <td>{$sl['name']} </td>
          <td>{$dl['name']} </td></tr>";
}