0

hello all i am having a variable $document_ids=1,2,4,5,8,99,102 and i need to insert each of them individually to my database table like

$shaeredata=mysqli_query
($conn,"insert into docs (dcid,pid) values 
('$dcid','$pid'),('$dcid2','$pid'),('$dcid3','$pid'),('$dcid4','$pid')");
//dcid is each id from the variable $document_ids=1,1022,4,5,8,99,102  
//$dcid=1,dcid2=1022,$dcid3=4 ...... pid is same for all

the problem is that how do i put the values to database as i dont what document_id is going to be there it can be any seperated by coma.

$document_id=Array
(
[0] => 1
[1] => 4
[2] => 5
[3] => 999
[4] => 6
[5] => 7
[6] => 8
) // i have converted it to an array all of these are $dcid $pid=23 for all

1 Answer 1

1

I assume you really mean that $documement_ids isarray(1,2,4,5,8,99,102). If it's a string, you can useexplode` to split it into an array.

You can create an array of all the value pairs, and then use implode to connect them with commas.

$values = implode(',', array_map(function($dcid) use ($pid) {
    return "('$dcid', '$pid')";
}, $document_ids);
$sql = "INSERT INTO docs (dcid, pid) VALUES $values";
mysqli_query($conn, $sql);
Sign up to request clarification or add additional context in comments.

10 Comments

is this possible to use more than two parameters in your function like if i want the $value to be like ('$dcid2','$pid','$something'),('$dcid3','$pid','$something') ???
You can add more variables to the use() list. use($pid, $something).
And if you have multiple arrays, you can add them to array_map(), and add more function parameters.
Make it a unique key, and use INSERT IGNORE to skip the ones that are duplicates.
Make a unique key on the list of columns that should be unique together. CREATE UNIQUE INDEX dcid_pid ON docs (dcid, pid);.
|

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.