$ row如何将所有数据转换为变量

时间:2013-06-19 18:19:54

标签: php mysql

我正在构建一个脚本完成的页面,它在表格中列出了Name和Points。但是当我要进行设计时,很难用“回声”做到这一点。所以我想知道我是否可以把它变成vars insted我可以在html文件中使用。

表格看起来像这样

姓名|积分|日期

我想要的是为10个名字行创建一个var,为10个第一个点行创建一个var。

$top1n = $row[0]'name'
$top1p = $row[0]'points'
$top2n = $row[1]'name'
$top2p = $row[1]'points'
$top3n = $row[2]'name'
$top3p = $row[2]'points'
$top4n = $row[3]'name'
$top4p = $row[3]'points'

等等......

请参阅下面的我的脚本

echo "<table border='1'>";

echo "<tr> <th>Name</th> <th>Tokens</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $resultbtm )) {
    // Print out the contents of each row into a table
    echo "<tr><td>"; 
    echo $row['Name'];
    echo "</td><td>"; 
    echo $row['points'];
    echo "</td></tr>"; 
} 

echo "</table>";

3 个答案:

答案 0 :(得分:0)

这是你想要的吗?

$names = array();
$points = array();

while($row = mysql_fetch_array($resultbtm)) {
    $names[] = $row['Name'];
    $points[] = $row['tokens'];
}

echo '<pre>';
print_r($names);
print_r($points);
echo '</pre>';

不是100%确定这是否是你要找的,但$names$points变量将是包含mysql结果集中的Names和Tokens(分别)的数组。

附注:由于安全问题,自PHP 5.5.0起不推荐使用mysql_*函数。如果您能够这样做,强烈建议您切换到mysqli_*PDO

答案 1 :(得分:0)

你可以这样做:(不需要创建这么多变量)

$str = "<table border='1'>";

$str .= "<tr> <th>Name</th> <th>Tokens</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $resultbtm )) {
    // Print out the contents of each row into a table
    $str .= "<tr>";
    $str .= "<td>".$row['Name']."</td><td>".$row['points']."</td>";
    $str .= "</tr>"; 
} 

$str .= "</table>";
echo $str;

答案 2 :(得分:-1)

您可以使用extract

    echo "<table border='1'>";

    echo "<tr> <th>Name</th> <th>Tokens</th> </tr>";
    // keeps getting the next row until there are no more to get
    $c = 1;
    while($row = mysql_fetch_array( $resultbtm )) {
        ${'top'.$c.'n'} = $name;
        ${'top'.$c.'p'} = $points;
        $c++;

        // Print out the contents of each row into a table
        echo "<tr><td>$Name</td><td>$tokens</td></tr>"; 
    } 

    echo "</table>";