如何将列的所有行添加到变量中?

时间:2012-03-28 18:42:58

标签: php mysql

想象一下,我有一个“id”列,每行包含一个数字。可以说我现在有3排。第1行包含1111,第2行包含2222,第3行包含3333。

我想将行值放入变量中,并用逗号分隔每行的数据。我期望的最终结果是$ variable = 1111,2222,3333。

我得到了这么远的代码:

<?php

    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("streamlist") or die(mysql_error());

    $sql = mysql_query("SELECT web_id FROM streams") or die(mysql_error());

        while($row = mysql_fetch_array($sql)) {

            $streamlist = $row['web_id'].",";

            echo $streamlist;

        }

?>

问题在于我需要单独获取每一行的信息:

<?php

    $numbers = explode(',', $streamlist);
    $firstpart = $numbers[0];

    echo $firstpart;

?>

上面的代码在while()语句中不起作用,也不是这样:

<?php

    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("streamlist") or die(mysql_error());

    $sql = mysql_query("SELECT web_id FROM streams") or die(mysql_error());

        while($row = mysql_fetch_array($sql)) {

            $streamlist = $row['web_id'].",";

        }

    $numbers = explode(',', $streamlist);
    $firstpart = $numbers[0];

    echo $firstpart;

?>

基本上,如何将行的所有信息都放入变量中,并用逗号分隔它们,然后单独得到每个数字?

3 个答案:

答案 0 :(得分:0)

$ streamlist范围似乎不对。尝试:

$streamlist = '';
while($row = mysql_fetch_array($sql)) {

        $streamlist .= $row['web_id'].",";

    }

答案 1 :(得分:0)

你走在正确的轨道上,尝试这个尺寸:

<?php

    mysql_connect("localhost", "root", "") or die(mysql_error());
    mysql_select_db("streamlist") or die(mysql_error());

    $sql = mysql_query("SELECT web_id, nextrow, nextrow2 FROM streams") or die(mysql_error());

    while($row = mysql_fetch_array($sql, MYSQL_NUM)){
        // $array_data will contain the array with all columns from the query (usable for your individual data needs as well)
        $array_data[] = $row;
        $var_string .= implode(",",$row);
        // $var_string will contain your giant blob comma separated string    
    }   
echo "<pre>"; print_r($array_data);echo "</pre>";
echo $var_string;
// These are for outputting the results
?>

答案 2 :(得分:0)

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("streamlist") or die(mysql_error());

$sql = mysql_query("SELECT web_id FROM streams") or die(mysql_error());
while($row = mysql_fetch_assoc($sql)) {

    $streamlist[] = $row['web_id'];

}

foreach ($streamlist as $row) {

    // Do whatever you want with the data
    echo $row.',';

}

$comma_separated = implode(",", $streamlist);