如何将以逗号分隔的数据添加到数据库
How to add data that separated with coma to database
我想将我的数据插入数据库。我有用逗号分隔的数据。
我试了一下,但看起来有点不对劲。
$rand_post = ["3001182708", "3001182713", "3001183215"];
$id_post = '123456';
$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));
$res = $sth->execute($prep);
我想像这样插入我的数据
id_post rand_post
============ ================
123456 3001182708
123456 3001182713
123456 3001183215
你很接近,但不是粘合字符串而是使用准备好的语句的力量。您 准备 查询,然后在循环中使用不同的参数执行它。也可以命名。
$rand_post = ["3001182708", "3001182713", "3001183215"];
$id_post = '123456';
$prep = array();
$sth = $db->prepare("INSERT INTO tes (`id_post`,`datas`) VALUES (?, ?)");
foreach($rand_post as $v ) {
$sth->execute(array($id_post, $v));
}
您可以找到更多信息here
这应该有效
$rand_post = ["3001182708", "3001182713", "3001183215"];
$id_post = '123456';
$prep = array();
foreach($rand_post as $v ) {
$prep[] = "($id_post, $v)";
}
$dataToInsert = implode(', ', $prep);
$sth = $db->prepare("INSERT INTO tes VALUES " . $dataToInsert);
$res = $sth->execute($prep);
我想将我的数据插入数据库。我有用逗号分隔的数据。
我试了一下,但看起来有点不对劲。
$rand_post = ["3001182708", "3001182713", "3001183215"];
$id_post = '123456';
$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));
$res = $sth->execute($prep);
我想像这样插入我的数据
id_post rand_post
============ ================
123456 3001182708
123456 3001182713
123456 3001183215
你很接近,但不是粘合字符串而是使用准备好的语句的力量。您 准备 查询,然后在循环中使用不同的参数执行它。也可以命名。
$rand_post = ["3001182708", "3001182713", "3001183215"];
$id_post = '123456';
$prep = array();
$sth = $db->prepare("INSERT INTO tes (`id_post`,`datas`) VALUES (?, ?)");
foreach($rand_post as $v ) {
$sth->execute(array($id_post, $v));
}
您可以找到更多信息here
这应该有效
$rand_post = ["3001182708", "3001182713", "3001183215"];
$id_post = '123456';
$prep = array();
foreach($rand_post as $v ) {
$prep[] = "($id_post, $v)";
}
$dataToInsert = implode(', ', $prep);
$sth = $db->prepare("INSERT INTO tes VALUES " . $dataToInsert);
$res = $sth->execute($prep);