如何使用php从数据库中提取逗号分隔的列值

时间:2014-09-18 07:48:06

标签: php mysql

在我的数据库表中有一个名为'标记'的列。 。它包含50,55,67,88等值,... 现在,我需要逐个读取这些值 - 先50,然后55,依此类推。如何使用PHP?

include("db_connect.php"); 
   $result = mysql_query("SELECT * FROM  students   ",$con);
   while($rows = mysql_fetch_array($result))
{
   $mark1=$rows['marks'];//what will do here
   $mark2=$rows['marks']; //should get value 55 and so on
}

5 个答案:

答案 0 :(得分:4)

如果您的值以逗号分隔,则展开该字段。

http://php.net/manual/en/function.explode.php

include("db_connect.php"); 
$result = mysql_query("SELECT * FROM  students", $con);

while($rows = mysql_fetch_array($result)) {
   $mark=explode(',', $rows['marks']);//what will do here
   foreach($mark as $out) {
      echo $out;
   }
}

答案 1 :(得分:2)

如果该行包含,,则只需使用explode()

while($rows = mysql_fetch_assoc($result)) {
    $mark1 = explode(',', $rows['marks']); // should contain the comma separated values
    // in array form
    // then loop again
    foreach($mark1 as $mark_piece) {
        // do something here
    }
}

答案 2 :(得分:2)

你应该使用爆炸功能

$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
  //your code to do something with the mark.
}

答案 3 :(得分:1)

从数据库中分解数据。使用explode function

使用索引访问:

while($rows = mysql_fetch_array($result)){
    $marks = $row['marks']; //get value of marks from the database

    $exp = explode("," , $marks); //explode marks data

    $mark1 = $exp[0]; //result is 50
    $mark2 = $exp[1]; //result is 55
    $mark3 = $exp[3]; //result is 67

}

或使用foreach循环

while($rows = mysql_fetch_array($result)){
    $marks = $row['marks']; //get value of marks from the database

    $exp = explode("," , $marks); //explode marks data

    foreach($exp as $mark) {
          echo $mark;
       }
}

答案 4 :(得分:0)

NB explode()函数将字符串分解为数组,它接受三个参数,第一个是分隔符,用于指定中断字符串的位置,第二个是需要拆分的字符串,第三个不是强制性的,但它告诉返回多少个数组。

$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];

有关explode()的更多信息请访问:http://php.net/manual/en/function.explode.php