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.
Related
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);
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.
I have a complicated array (at least it looks complicated to me). I have a form where you select a person, a start time and an end time. You can then add more people by clicking a + button. So I named the three select fields like "select_dancer[]" for an array.
When I print_r my results, it looks like this:
Array
(
[month_year] => 2011-11
[select_dancer] => Array
(
[0] => 1
[1] => 2
)
[time_from] => Array
(
[0] => 12:00pm
[1] => 1:00pm
)
[time_to] => Array
(
[0] => 12:30pm
[1] => 1:30pm
)
)
Basically, the key 0 is one person, and key 1 is another. Etc. I'm having trouble getting my head around adding this to the database. My table is basically: id, date, dancer, from, to. So I want it so I can "group" each key together and submit the values to the database.
If anyone could help me out, that would be great.
An easier approach to the field grouping would be something like this in your HTML
<input name="dancer[0][id]" ...
<input name="dancer[0][time_from]" ...
<input name="dancer[0][time_to]" ...
As each group is added, increment the number in the first square-brackets.
Your resulting $_POST array would then look like
Array
(
[month_year] => 2011-11
[dancer] => Array
(
[0] => Array
(
[id] => 1,
[time_from] => 12:00pm
[time_to] => 12.30pm
)
[1] => Array
(
[id] => 2
[time_from] => 1:00pm
[time_to] => 1:30pm
)
)
)
You can then iterate the $_POST['dancer'] array for each group of values, eg (very simplified)
foreach ($_POST['dancer'] as $dancer) {
if (!isset($dancer['id'], $dancer['time_from'], $dancer['time_to'])) {
throw new Exception('All fields are required');
}
$id = $dancer['id'];
$timeFrom = $dancer['time_from'];
$timeTo = $dancer['time_to'];
}
Try something like this:
for ($i = 0; $i < count($mydata["select_dancer"]); $i++)
{
$insert = "insert into mytable (date, dancer, from to) values ($mydata['month_year'], $mydata['select_dancer'][$i], $mydata['time_from'][$i], $mydata['time_to'][$i])";
do_sql_insert($insert);
}
With this, you're vulnerable to injection attacks and the chance that a particular dancer doesn't have a represented index in every sub-array. Go with what #Phil wrote if you can.
If each of element select_dancer, time_from, time_to has the same array size, you can easily check for any of that and do loop using it:
WARNING: UNTESTED CODE
foreach($post_array['select_dancer'] as $key => $value)
{
$sql = "INSERT INTO dance_table(date, dancer, from, to) ";
$sql .= "VALUES('{$wherever_you_got_the_date}', '{$value}',";
$sql .= "'" . $post_array['time_from'][$key] . "', ";
$sql .= "'" . $post_array['time_from'][$key] . "')";
}
foreach($_POST[select_dancer] as $key => $value) {
$sql = "insert into table set dancer=$value,from='{$_POST['time_from'][$key]}',to={$_POST['time_to'][$key]}';"
//execute the SQL ...
}
of course in real life got to deal will protecting against SQL injection etc, but the principle of accessing the arrays is the same
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']);
}
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