0

我有餐桌人。

id, age
--  -----
1   2
2   5
3   6
4   7
5   8

我想从年龄中得到一个值。我下面的代码的结果是 25678。我怎样才能得到一个值。

$query= "SELECT age FROM person";
$result= mysql_query($query) or die ("Query error: " . mysql_error());
while($row = mysql_fetch_array($result))
    {
     $age= $row['age'];  
     echo $age; // the result will be 25678
     // i want to get a value from the result ex = 5 or 6
     //I try with call the index like my code bellow but It's not working
         echo $age[1]; 
         echo $age[2]; 
    }

有人可以帮我吗...

4

5 回答 5

0
while($row = mysql_fetch_array($result)) {
  $age = $row[0];
  echo $age."<br />";
}

While loop will run until the end of $result array. In each loop, it will echo current row.

于 2013-06-01T02:10:09.803 回答
0

好吧,如果你想要一个时代。将所有行保存在数组中并获取您选择的索引。

例子:

 $query= "SELECT age FROM person";
    $result= mysql_query($query) or die ("Query error: " . mysql_error());
    $ageArray;
    $i=0;
    while($row = mysql_fetch_array($result))
        {
         //$age= $row['age'];  
         $ageArray[$i++]=$row['age'];
        }
    echo $ageArray[1];

我希望这是你想要的...

于 2013-06-01T03:22:53.393 回答
0

尝试这个

$query= "SELECT age FROM person";
$result= mysql_query($query) or die ("Query error: " . mysql_error());
$array_r;
while($row = mysql_fetch_array($result))
    {
       array_push($array_r,$row['age']);
    }

echo '<pre/>';
print_r($array_r);
于 2013-06-01T04:00:31.360 回答
0

在你的情况下,我想到了两件事:

1.通过传递条件来查询: 由于您只想获取一个值,那么您应该必须根据id字段传递一个条件,这样您就只会得到一个值

$query= "SELECT age FROM person where id={$id}"; //here $id may be any numeric value which you have specified
$result= mysql_query($query) or die ("Query error: " . mysql_error());
$age = mysql_fetch_assoc($result);
if(count($age)){
    echo $age[0]['age']; //this will print only single value based on condition you have specified in SQL query
}

2.通过将结果(年龄)分配给一个数组,然后打印

$query= "SELECT age FROM person";
$result= mysql_query($query) or die ("Query error: " . mysql_error());
$age = array();
while($row = mysql_fetch_array($result))
{
    $age[] = $row['age'];
}

echo "<pre>";
print_r($age);

echo $age[1]; //this will print 5
echo $age[2]; //this will print 6
于 2013-06-01T04:18:38.390 回答
0

尝试这个

$query= "SELECT age FROM person";
$result= mysql_query($query) or die ("Query error: " . mysql_error());
//take age in an array
$age=array();
while($row = mysql_fetch_array($result))
    {

     array_push($age, $row['age']);
     echo $row['age'];  // the result will be 25678

     // i want to get a value from the result ex = 5 or 6
     //I try with call the index like my code bellow but It's not working
         echo $age[1]; 
         echo $age[2]; // now u will get desired result by calling index of $age array
    }
于 2013-06-01T06:37:54.453 回答