0

我有这段代码可以从 mysql 数据库中获取数据。

<?php
$sql = mysql_query( "SELECT * FROM users WHERE name = $name" );
while ( $row = mysql_fetch_array( $sql ) ) {
 echo $row[id] . '|';
 echo $row[name] . '|';
 echo $row[add] . ':';
}
OUTPUT : 12|jonathan|philippines:14|John|england:
?>

如何删除 :使用 while 的最后一个分隔符?

4

4 回答 4

2
$sql = mysql_query( "SELECT `id`, `name`, `add` FROM users WHERE name = $name" ); 
$data = array();
while ( $row = mysql_fetch_array( $sql, MYSQL_NUM ) ) 
{  
  $data[] = implode('|', $row);
} 
echo implode(':', $data);

如果你这样做,它会更健壮一点,如果你现在改变你的查询也没关系......它只会以你想要的格式输出你的字段

于 2012-07-13T11:26:23.493 回答
1
$sql = mysql_query( "SELECT * FROM users WHERE name = $name" );
$counter = 0;
while ( $row = mysql_fetch_array( $sql ) ) {

   if ($counter > 0) {
       echo ":";
   }
   echo $row[id] . '|' . $row[name] . '|' . $row[add];
   $counter++;
}
于 2012-07-13T11:20:20.550 回答
0
<?php
$out = '';
$sql = mysql_query( "SELECT * FROM users WHERE name = $name" );
while ( $row = mysql_fetch_array( $sql ) ) {
 $out.=$row[id] . '|';
 $out.=$row[name] . '|';
 $out.=$row[add] . ':';
}
echo substr($out,0,-1);
?>
于 2012-07-13T11:21:20.383 回答
0
    $sql = mysql_query( "SELECT * FROM users WHERE name = $name" );
    $number = mysql_num_rows($sql);
    $i = 1;
       while ($row = mysql_fetch_assoc($sql)) {
             echo $row[id] . '|';
             echo $row[name] . '|';
             echo $row[add] ;

       if($i < $number) {
           echo ':';
        }
       $i++;
    }
于 2012-07-13T11:21:23.790 回答