选择后如何访问所有行的列值?

时间:2014-01-10 22:58:42

标签: php

我有以下代码设置和mysql_num_rows echos 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;

4 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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;
}

答案 2 :(得分:0)

切换到fetch_all

foreach (mysql_fetch_all($item_query) as $row) {
    $id = $row['id'];
    // Do all the stuff you want to do here
}

为了热爱编程,请停止使用mysql_函数!请看这里的大红框:

http://us2.php.net/manual/en/function.mysql-query.php

答案 3 :(得分: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"];
}