inserting to database in one shot an array mysql - php

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

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

Related

SQL result array, from PDO query, has duplicated values [duplicate]

This question already has answers here:
sql PDO fetchall duplicate object keys?
(2 answers)
Closed 2 years ago.
I have a mysql table that has the following fields
STUDENTID | FIRSTNAME | SURNAME | DOB | SCHOOLID
A form is used for a user to search for a student and output all those with matching first and surnames
The following SQL statement returns the PDO fine
$sqlstmnt2 = 'SELECT * FROM students WHERE firstName = :fname AND surname = :sname AND schoolID = :schoolID';
// prepare PDOstatement as $query ...
// ...
$query->execute();
$_SESSION['foundPupils'] = $query->fetchAll();
However, when I pass this through to another PHP page in a session variable, I'm confused as to how to access each field individually. I have the following code
foreach($_SESSION['foundPupils'][0] as $found){
echo($found);
}
This outputs the found data but the issue is that it outputs it twice, and it's just a long string of data which can't be formatted nicely. My questions are:
Why does each result output twice?
How do I access the individual fields within this array (kind of like foundPupils[0]['firstName'] for example?
According to the documentation, both the method PDOStatement::fetch and PDOStatement::fetchAll accepts a $fetch_style parameter. If not set, the default value is PDO::FETCH_BOTH. That means the fetched array will both reference the fields by position (e.g. 0, 1, 2) and by column name (e.g. "firstName", "surname").
So by default, your fetched results would be something like this:
Array
(
[0] => Array
(
[name] => apple
[0] => apple
[colour] => red
[1] => red
)
[1] => Array
(
[name] => pear
[0] => pear
[colour] => green
[1] => green
)
[2] => Array
(
[name] => watermelon
[0] => watermelon
[colour] => pink
[1] => pink
)
)
To fix this, you need to call your fetch function (I suppose it is PDOStatement::fetchAll) with PDO::FETCH_COLUMN as the fetch style:
$query->execute();
$_SESSION['foundPupils'] = $query->fetchAll(PDO::FETCH_COLUMN);
Query results are returned and stored in a result object. Therefore, you have to iterate through the result either using xxxx_fetch_array or xxxx_fetch_row. for example
$sql='SELECT * FROM table_name';
$result = mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
echo $row['COLUMN_NAME'].'<br />';
}

merge two arrays with numeric keys for values of associative array to insert in MySQL in multiple rows

I'm getting two arrays $post_img & $post_sort resulting:
Array
(
[0] => test1.jpg
[1] => test2.jpg
[2] => test3.jpg
)
Array
(
[0] => 3
[1] => 1
[2] => 2
)
I'd like to merge them like:
Array
(
[Image] => Array
(
[0] => test1.jpg
[1] => test2.jpg
[2] => test3.jpg
)
[Sort] => Array
(
[0] => 3
[1] => 1
[2] => 2
)
)
Because I think its the best way to insert them into my Database each entry in one row like:
ID | Image | Sort
1 test1.jpg 3
2 test2.jpg 1
3 test3.jpg 2
The point is that I think this should be possible with only one query.
I had different tries but none of them ended up good.
Using a multiple iterator
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($post_img));
$mi->attachIterator(new ArrayIterator($post_sort));
foreach ( $mi as $value ) {
list($filename, $sortOrder) = $value;
echo $filename , ' => ' , $sortOrder , '<br />';
}
might make it easier to process both arrays at the same time for your database inserts
Use array:
$newarray = array('Image' => $post_img, 'Sort' => $post_sort);
For adding the data to your table, you can go with your original arrays:
$sql = "INSERT INTO tablename SET Image=:image, Sort=:sort";
$dbImgInsert = $db->prepare($sql); // preparing sql for insert, using parameters
$c = count($post_img)-1;
for ($i=0;$i<=$c;$i++;) { // looping through the arrays
$dbImgInsert->execute(array( // inserting the data into the prepared query and into the db
'image' => $post_img[$i],
'sort' => $post_sort[$i]
));
} // for
The above example assumes you are using MySQL with PDO.
To create a single INSERT-statement the classic way, go:
$sql="";
$c = count($post_img)-1;
for ($i=0;$i<=$c;$i++;) { // looping through the arrays
$sql.="('{$post_img[$i]}', '{$post_sort[$i]}'), ";
}
$sql ="INSERT INTO tablename (Image, Sort) VALUES " . trim($sql,',');
There is no point merging the arrays, you can just do a SQL statement like so:
INSERT INTO tbl (Image, Sort) VALUES
($post_img[0], $post_sort[0]),
($post_img[1], $post_sort[1]),
($post_img[2], $post_sort[2]),
($post_img[3], $post_sort[3])
The latter half of that query can be generated using a loop of some sort.

If value exists in one PHP array, add value to second array

I have two PHP arrays. One contains a group name and another contains a pay wage value.
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 1 [3] => 3 );
This means there are four employees on the schedule. Two are assigned to group 1, another to group 4 and the last to group 3.
The second array is as follows:
$tot_wages_array = Array ( [0] => 500 [1] => 44 [2] => 80 [3] => 11.25 );
This is a sample array of each employee's wage. Both arrays are constructed in order as values are added in a mysql while loop as it pulls the info from the database.
Later on down the line, I combine the two arrays to get one array where the key is the group number and the value is the total wages for that group:
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
This works like a charm EXCEPT for when more than one employee is assigned to the same group. These arrays are built in a mysql while loop as it loops through each employee's info:
array_push($tot_wages_array, $totemp_wages_sch); // Add their wage to the array
array_push($group_wages_array, $emp_data['group_id']); // Add their group to the array
Instead of just pushing the data to the array, I need to do this... I know the english but I don't know how to code it:
If $emp_data['group_id'] exists as value in $group_wages_array, add nothing to this array but get the key. Add $totemp_wages_sch to $tot_wages_array where key = group_wages_array key
I know it sounds more like an SQL query but I have to keep the keys and values in order so that they can be combined later in the page. If I can get this to work right, The arrays shown in the example would be:
$group_wages_array = Array ( [0] => 1 [1] => 4 [2] => 3 );
$tot_wages_array = Array ( [0] => 580 [1] => 44 [2] => 11.25 );
$combined_group_wages = array_combine($group_wages_array, $tot_wages_array);
$combined_group_wages = Array ( [1] => 580 [4] => 44 [3] => 11.25 );
...I've got to make this work using PHP. Any ideas?
I came up with a solution based on a combination of two of the answers submitted below. Here it is if it can help someone:
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] += $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
array_push($tot_wages_array, $totemp_wages_sch);
}
This should do it:
$group_wages_array = array(1, 4, 1, 3);
$tot_wages_array = array(500, 44, 80, 11.25);
$combined_group_wages = array();
for ($i=0; $i<count($group_wages_array); $i++) {
$group = $group_wages_array[$i];
if (array_key_exists($group_wages_array[$group], $combined_group_wages)) {
$combined_group_wages[$group] += $tot_wages_array[$i];
} else {
$combined_group_wages[$group] = $tot_wages_array[$i];
}
}
print_r($combined_group_wages);
Yields:
Array
(
[1] => 580
[4] => 44
[3] => 11.25
)
But I recommend that you just switch to using objects to better represent your data.
If I could see the entirety of the code that would help a lot, but here's your English converted to php. Show me more code and I can perfect it, until then try this ->
if(in_array($emp_data['group_id'], $group_wages_array)){
$key = key($group_wages_array);
$tot_wages_array[$key] = $totemp_wages_sch;
} else {
array_push($group_wages_array, $emp_data['group_id']);
}

PHP Array insert into MySQL table as individual rows

I am trying to insert multiple rows in a MySQL table from PHP arrays. I managed with with help of other members to get set of values in a pair of brackets but when i try to insert this i get "Error: Column count doesn't match value count at row 1" I donot know where am i going wrong. my codes are as below: (The number of values i get vary according to user input)
$docno1=array();
$serialno = array();
$acc_name = array();
$debit = array();
$credit = array();
for ($i=1;$i<=$rowcount;$i++)
{
//echo 'Accountname'.$i.' :'.($_GET['accname'.$i]).'<br>';
$docno1 [] = ($_GET['docno']);
array_unshift($docno1,"");
unset($docno1[0]);
$serialno [] = $i;
array_unshift($serialno,"");
unset($serialno[0]);
$acc_name[] = ($_GET['accname'.$i]);
array_unshift($acc_name,"");
unset($acc_name[0]);
$debit[] = ($_GET['DrAmount'.$i]);
array_unshift($debit,"");
unset($debit[0]);
$credit[] = ($_GET['CrAmount'.$i]);
array_unshift($credit,"");
unset($credit[0]);
}
$sum_dr = array_sum ($debit);
$sum_cr = array_sum ($credit);
echo ' values of $multi<br>';
$multi = array(
($docno1),
($serialno), //Array for a row of fields
($acc_name),
($debit),
($credit),
($docno1)
);
print_r($multi);
$new = array();
foreach($multi as $key=>$value) {
$new[] = "'".implode("','", $value)."'";
}
echo '<br>Values of $new <br>';
print_r($new);
$query = "(".implode("), (",$new).")";
echo $query.'<br>';
mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());
echo "Inserted successfully";
die;
The results i get are :
values of $multi
Array
(
[0] => Array
(
[1] => 3434
[2] => 3434
)
[1] => Array
(
[1] => 1
[2] => 2
)
[2] => Array
(
[1] => Lemon
[2] => Kidney Beans
)
[3] => Array
(
[1] => 20
[2] => 10
)
[4] => Array
(
[1] => 0
[2] => 0
)
[5] => Array
(
[1] => 3434
[2] => 3434
)
)
Values of $new
Array
(
[0] => '3434','3434'
[1] => '1','2'
[2] => 'Lemon','Kidney Beans'
[3] => '20','10'
[4] => '0','0'
[5] => '3434','3434'
)
('3434','3434'), ('1','2'), ('Lemon','Kidney Beans'), ('20','10'), ('0','0'), ('3434','3434')
Error: Column count doesn't match value count at row 1
mysql_query("INSERT INTO docitems (`docno`,`itemno`,`accountname`,`debit`,`credit`, `picrefno`) VALUES ".$query.";") or die('Error: ' . mysql_error());
You are trying to insert something into 6 fields, so that $query string must have 6 values in it, or you get this error.
You have a lot of $query's that are 2 values. And that's not 6
It looks to me as if you are mapping your array the wrong way round. You're trying to add two records with six fields each, but what you're actually putting into the SQL statement are six records with two fields each.
This is why MySQL is complaining -- because you've told it you want to update six fields, but in each of the records you've given it, you've only specified two fields.
You need to build your array differently.
I assume that $docno1, $serialno, $acc_name, $debit and $credit will always all have the same number of array elements (it appears from your code that you are assuming this, so I'll follow you in your assumption).
In that case, you need to build your array something like this:
$multi = array();
foreach($docno1 as $key=>value) {
$multi[] = array(
$docno1[$key],
$serialno[$key], //Array for a row of fields
$acc_name[$key],
$debit[$key],
$credit[$key],
$docno1[$key])
}
Replace the block in your code where you set $multi with this, and your program should work.
Look at what print_r($multi) looks like now, and you'll see the difference.
(note, there are more efficient ways of writing your whole program than this, but I've focused on giving you a drop-in replacement for this specific bit, to help show you where you were going wrong, rather than simply rewriting the whole program for you)
Hope this helps.
If the error is occurring when trying to insert a row to your table, try specifying the list of fields, in the insert query -- this way, the number of data in the values clause will match the number of expected columns.
Else, MySQL expects six columns : it expects the specific inserts -- for which you didn't specify a value.

Inserting values from multidim. array using PDO takes a long time. Is there a better way?

I got an array of 650 rows. Inserting this using PDO takes between 10-15 seconds on my local computer.
That's very slow. Is this because of disk read/write? Or could it be something else?
This is my array (first 4 rows):
Array
(
[0] => Array
(
[0] => 3
[1] => 1
)
[1] => Array
(
[0] => 3
[1] => 2
)
[2] => Array
(
[0] => 3
[1] => 5
)
[3] => Array
(
[0] => 8
[1] => 1
)
)
And this is my code:
$stmt = $this->db->prepare("INSERT INTO sl_link_store_category (item_a_ID, item_b_ID) VALUES (:item_a_ID, :item_b_ID)");
foreach($my_array as $row) {
$stmt->execute(array(':item_a_ID' => $row[0], ':item_b_ID' => $row[1]));
}
SOLUTION
For those who is wondering, her eis my solution for inserting multiple rows
using only one $stmt->execute:
$input_arr; // This array one has lots of values
$sql = "INSERT INTO sl_link_store_category (field_a, field_b) VALUES ";
$i = 0;
// I create the query string with unique prepared values
// I could probably have used a for loop since I'm not using any
// values from $row
foreach($input_arr as $row) {
$i++;
$sql .= "(:field_a_$i, :field_a_$i), ";
}
// Remove the last comma (and white space at the end)
$sql = substr(trim($sql), 0, -1);
$stmt = $this->db->prepare($sql);
// I need to create a new associative array with field name
// matching the prepared values in the SQL statement.
$i = 0;
$arr = array();
foreach($input_arr as $row) {
$i++;
$arr[":field_a_$i"] = $row[0];
$arr[":field_b_$i"] = $row[1];
}
$stmt->execute($arr);
}
The reason it might be that slow can vary based on alot of factors.
Consider using one query to insert multiple records PDO Prepared Inserts multiple rows in single query

Categories