获取一个字段中的所有行数据

时间:2017-02-23 18:07:12

标签: php mysql

$stmt = $db->query("SELECT c.id, c.name FROM (SELECT @r AS _id, (SELECT @r := parent FROM categories WHERE id = _id) AS parent, @l := @l + 1 AS lvl FROM (SELECT @r := 74, @l := 0) vars, categories m WHERE @r <> 0) m JOIN categories c ON m._id = c.id ORDER BY m.lvl DESC;");           
                    while($bread = $stmt->fetch()){                         
                        $plip = $bread['name'];
                        $each = "$plip-";
                        echo $each;
                        echo "<label value='$each'></label>";                                   

                    }

echo $each给出了这个输出:“Milk-Cat-Cookie”,这就是我想要的,所以很好。

但是回显<label value='$each'></label>给出了这个输出:<label value='Milk-'></label>

但必须如此:<label value='Milk-Cat-Cookie'></label>

那么为什么我不能在一个字段中显示所有行数据呢?

2 个答案:

答案 0 :(得分:3)

尝试将回声<label value='$each'></label>;行放出&#34;而&#34; sintax,像这样:

while($bread = $stmt->fetch()){                         
    $plip = $bread['name'];
    $each = "$plip-";
    echo $each;
}
echo "<label value='$each'></label>"; 

请注意,我在$each变量的结果的每次迭代上都会结束。

答案 1 :(得分:0)

$stmt = $db->query("SELECT c.id, c.name FROM (SELECT @r AS _id, (SELECT @r := parent FROM categories WHERE id = _id) AS parent, @l := @l + 1 AS lvl FROM (SELECT @r := 74, @l := 0) vars, categories m WHERE @r <> 0) m JOIN categories c ON m._id = c.id ORDER BY m.lvl DESC;");           
                    while($bread = $stmt->fetch()){                         
                        $plip = $bread['name'];
                        $each = "$plip-";
                        echo $each;
                        echo "<label value='$each'></label>";                                   

                    }

应该是:

$stmt = $db->query("SELECT c.id, c.name FROM (SELECT @r AS _id, (SELECT @r := parent FROM categories WHERE id = _id) AS parent, @l := @l + 1 AS lvl FROM (SELECT @r := 74, @l := 0) vars, categories m WHERE @r <> 0) m JOIN categories c ON m._id = c.id ORDER BY m.lvl DESC;");           
                    echo "<label value='";
                     $each='';
           while($bread = $stmt->fetch()){                         
                        $plip = $bread['name'];
                        $each .= "$plip-";


                }
                 echo $each;  
             echo "'></label>";

我在循环中只留下了变量echo。顺便说一下你的代码你应该修剪最后 - 还是可以留下它?