0

i want to insert my data to database. i have data that separated with commas.

i try like this but look like something wrong.

$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);

i want to insert my data like this

id_post            rand_post
============       ================
123456             3001182708
123456             3001182713
123456             3001183215
1
  • During prepare statement, you pass ? instead of the $prep array Commented Sep 3, 2018 at 7:36

2 Answers 2

1

You are close but instead of gluing the strings use the power of prepared statements. You prepare the query and then in the loop you execute it with different params. Can be named as well.

$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));
}

You can find more information here

Sign up to request clarification or add additional context in comments.

4 Comments

Bad practice. you should avoid queries inside loops.
@MaratBadykov it isn't a bad practice to execute prepared statement inside the loop. It's different than executing query itself. Don't bring confusion to the OP.
In general, it's usually better performance-wise to do bulk or batch queries than queries in a loop, since you can save round trip calls to the DB.
@MaratBadykov it'd make difference if the dataset was really big.
0

This should work

$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);

3 Comments

Sorry, i was wrong with syntax. I updated answer, pls test
Using answer from Robert is bad practice, you shoul avoid queries inside loops.
@MaratBadykov it's better than gluing strings instead of using prepared statements, and it's quite common practice. The query is prepared on db side and what it actually does is binding the parameters to this prepared query. For sure it's better solution than the one that you propose. Cheers .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.