如何将以逗号分隔的数据添加到数据库
How to add data that separated with comas to database
我想将我的数据插入数据库。我有用逗号分隔的数据。
例如我有这样的数据:
$rand_post = ["3001182708", "3001182713", "3001183215"];
$id_post = '123456';
这是我在网上搜索后得到的最佳答案
$prep = array();
foreach($rand_post as $k => $v ) {
$prep[':'.$k] = $v;
}
print_r($prep);
$sth = $db->prepare("INSERT INTO tes (`datas`) VALUES (" . implode('), (',array_keys($prep)) . ")");
$res = $sth->execute($prep);
但它只是为 $rand_post
插入数据
我想像这样插入我的数据
id_post rand_post
============ ================
123456 3001182708
123456 3001182713
123456 3001183215
尝试 splash 的回答后
id_post rand_post
============ ================
123456 2147483647
123456 2147483647
123456 2147483647
在循环中结对
$prep = array();
foreach($rand_post as $v ) {
$prep[] = "($id_post, $v)";
}
print_r($prep);
$sth = $db->prepare("INSERT INTO tes (`id_post`,`datas`) VALUES " . implode(', ', $prep));
// INSERT INTO tes (`id_post`,`datas`) VALUES (123456, 3001182708), (123456, 3001182713), (123456, 3001183215)
$res = $sth->execute($prep);
我想将我的数据插入数据库。我有用逗号分隔的数据。
例如我有这样的数据:
$rand_post = ["3001182708", "3001182713", "3001183215"];
$id_post = '123456';
这是我在网上搜索后得到的最佳答案
$prep = array();
foreach($rand_post as $k => $v ) {
$prep[':'.$k] = $v;
}
print_r($prep);
$sth = $db->prepare("INSERT INTO tes (`datas`) VALUES (" . implode('), (',array_keys($prep)) . ")");
$res = $sth->execute($prep);
但它只是为 $rand_post
我想像这样插入我的数据
id_post rand_post
============ ================
123456 3001182708
123456 3001182713
123456 3001183215
尝试 splash 的回答后
id_post rand_post
============ ================
123456 2147483647
123456 2147483647
123456 2147483647
在循环中结对
$prep = array();
foreach($rand_post as $v ) {
$prep[] = "($id_post, $v)";
}
print_r($prep);
$sth = $db->prepare("INSERT INTO tes (`id_post`,`datas`) VALUES " . implode(', ', $prep));
// INSERT INTO tes (`id_post`,`datas`) VALUES (123456, 3001182708), (123456, 3001182713), (123456, 3001183215)
$res = $sth->execute($prep);