php mysql-将mysql_fetch_array()导入字符串并用逗号分隔字符串

时间:2015-04-08 07:20:53

标签: php mysql string

我在这里有一个mysql表(请求):

request:
r_id     item_no
  1         1
  13        10
  22        20
  33        30 
  55        40

现在,我正在使用php使用mysql_fetch_array()取出r_id并尝试将mysql_fetch_array()结果放入字符串中,并用逗号分隔字符串。

<?php   
include('config.php'); //connect to mysql
function f(){
    $sql = "SELECT r_id FROM `request` ";
    $result=mysql_query($sql);
    $string = '';
    $i = 0; 
    while ($row = mysql_fetch_array($result)) {
        $string .= $row[$i];
    }
    $newstring = implode(", ", preg_split("/[\0-9]+/", $string));
    return  $newstring ;
}

$get=f();
echo $get;
?>

但我无法从我的PHP代码中获得正确的字符串。

我想得到像

这样的字符串
1,13,22,33,55

我该如何解决问题?

4 个答案:

答案 0 :(得分:4)

你不需要拆分它并内爆,只需这样做:

while ($row = mysql_fetch_array($result)) {
    $string .= $row[$i].',';// append comma after each value you append to the string
}
return substr($string,0,-1);// cut off the trailing comma from the final string

答案 1 :(得分:0)

试试我的最新回答:

$sql = "SELECT r_id FROM `request` ";
$result=mysql_query($sql);
$string = '';
$i = 0; 
while ($row = mysql_fetch_array($result)) {
    $string .= $row[$i].",";
}
return  $string ;
}

答案 2 :(得分:0)

<?php   
include('config.php'); //connect to mysql
function f(){
    $sql = "SELECT GROUP_CONCAT(r_ID) FROM `request` ";
    $result=mysql_query($sql);
    return  $result ;
}

$get=f();
echo $get;
?>

答案 3 :(得分:0)

$array = array();
while(...){
   $array = $row[$i]; //first you need array 
}
$string = implode(",",$array); //now you have your string