Reputation: 169
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?
Upvotes: 2
Views: 2299
Reputation: 64
$array = array();
while(...){
$array = $row[$i]; //first you need array
}
$string = implode(",",$array); //now you have your string
Upvotes: 0
Reputation: 3868
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 ;
}
Upvotes: 0
Reputation: 9420
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
Upvotes: 4
Reputation: 4739
<?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;
?>
Upvotes: 0