2014-01-10 81 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

相關問題