如何在mysql中的不同列中插入不同的逗号分隔值

时间:2013-11-18 08:55:17

标签: php mysql comma

我从不同的coloumn (supplierrouteallocation:1000,1200 and routesymbol:10xx,12xx)中取出数据库中的两个逗号分隔值,我想将此值插入到另一个表中,插入到不同的列中,例如像这样

route    symbol

1000     10xx

1100     11xx

但是我试过它不工作可以任何人帮助。谢谢

我的代码

$routes = explode(",",$supplierrouteallocation);
$symbol = explode(",",$routesymbol);

$count=count($routes,$symbol);
for($i=0;$i<$count;$i++)
{

$sql_insertroute="INSERT INTO `fms`.`routestable` (
    `id` ,  

`route` 
`routesymbol`       
)
VALUES (NULL ,'$routes[$i]','$symbol[$i]')
";

mysql_query($sql_insertroute);

}

2 个答案:

答案 0 :(得分:2)

你有各种各样的错误:

  • count()只接受一个数组
  • 您在请求中错过了一个昏迷:('id', 'route'[,] 'routesymbol')

这是一段适用于您的代码:

// get data
$routes = explode(",",$supplierrouteallocation);
$symbols = explode(",",$routesymbol);

// prepare the request
$sql_insertroute = "INSERT INTO `fms`.`routestable` (`id`, `route`, `routesymbol`) VALUES ";

// create an insert line per data couple
$vals = array();
$n = max(count($routes), count($symbols));
for($i=0;$i<$n;$i++) {
    $route = isset($routes[$i]) ? "'".$routes[$i]."'" : "NULL";
    $symbol = isset($symbols[$i]) ? "'".$symbols[$i]."'" : "NULL";
    array_push($vals, "(NULL, $route, $symbol)");
}

// join those lines with comas, and add'em to the request
$sql_insertroute .= implode(', ', $vals);

答案 1 :(得分:0)

试试这个

$sql_insertroute="INSERT INTO `fms`.`routestable` (`id`,`route`,`routesymbol`) VALUES (NULL,'".$routes[$i]."','".$symbol[$i]."')";