2

I have a mysql table(request) here:

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

Now, I'm using php to take r_id out using mysql_fetch_array() and try to put mysql_fetch_array() result in to a string also split the string by comma.

<?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;
?>

But I cannot get the right string form my php code.

I want to get the string like

1,13,22,33,55

How can I fix the problem?

1
  • what you are getting?? Commented Apr 8, 2015 at 7:31

4 Answers 4

4

You don't need to split that and implode, just do this:

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
Sign up to request clarification or add additional context in comments.

Comments

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;
?>

Comments

0

Try my updated answer:

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

Comments

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

1 Comment

always follow the stackover flow standards for giving the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.