2014-01-10 41 views
0

我有下面的代码设置和mysql_num_rows回声2,因为它应该是。 我想以某种方式访问​​已被选中的第二行,但无法弄清楚如何。 echo $ lTitl总是以随机顺序从第一行返回标题,但我还想在此之后访问行。我该怎么做呢?如何在选择它们后访问所有行的列值?

$sql = "SELECT id, seller, title, kondition, price, shippingcost FROM items WHERE active='1' ORDER BY rand() LIMIT 2"; 
$item_query = mysql_query($sql, $connect); 

foreach ($row = mysql_fetch_assoc($item_query) as $test) { 
    $id = $row["id"]; 
    $seller = $row["seller"]; 
    $lTitl = $row["title"]; 
    $lCond = $row["kondition"]; 
    //$lPrimIma = $row["primaryimage"]; 
    $lPric = $row["price"]; 
    $lShip = $row["shippingcost"]; 
} 
echo $lTitl; 
+0

mysql_fetch_assoc()只返回一个行,所以你的foreach(mysql_fetch_assoc()为$测试)只会循环一次。你想mysql_fetch_all – Rottingham

+0

看到我的答案@willi http://stackoverflow.com/a/21056095/1607528 – 2014-01-10 23:07:41

回答

1

您可以通过循环
当您需要使用mysql_fetch_all检索多个列的阵列中存储的值做这样的事情。
请注意,mysql函数已被弃用。使用mysqli or PDO instead

foreach ($row = mysql_fetch_all($item_query) as $test) { 
$id[] = $row["id"]; 
$seller[] = $row["seller"]; 
$lTitl[] = $row["title"]; 
$lCond[] = $row["kondition"]; 
//$lPrimIma = $row["primaryimage"]; 
$lPric[] = $row["price"]; 
$lShip[] = $row["shippingcost"]; 
} 
echo $lTitl[0]; // will print first row 
echo $lTitl[1]; // will print second row 
0

保存到$test结果。你必须改变这个:

while ($test = mysql_fetch_assoc($item_query)) { 
    $id = $test["id"]; 
    $seller = $test["seller"]; 
    $lTitl = $test["title"]; 
    $lCond = $test["kondition"]; 
    //$lPrimIma = $test["primaryimage"]; 
    $lPric = $test["price"]; 
    $lShip = $test["shippingcost"]; 
} 
1
$one = mysql_fetch_assoc($item_query); 
$second = mysql_fetch_assoc($item_query); 

echo $one["title"]; // first title 
echo $second["title"]; // second title 

**EDIT** 
$titles = array(); 
while ($row = mysql_fetch_assoc($item_query)) { 
    $title[] = $row['title']; 
} 

foreach($titles as $title){ 
    echo $title; 
} 
+0

希望结果集只能结束两个项目!通过显示可重复使用的动态代码来提高OP的技能。 – Rottingham

+0

@Rottingham我知道。见'极限2'。他只需要两行。没有循环。为什么? – voodoo417

+1

因此,当他删除“极限2”并想要第三个,那么是什么?再加上$ third = ...和$ fourth = ... – Rottingham

相关问题