Saving multiple HTML textareas in CodeIgniter - php

I would like to grab the values of several textarea fields and save them to the database. For now I have four of each with different values and I want to batch save these values, the textarea fields are:
<textarea name="compedia[]"></textarea>
<textarea name="specification[]"></textarea>
and the save function:
function saveCOA(){
$labref=$this->uri->segment(3);
$data= $this->input->post('compedia');
$data1= $this->input->post('specification');
$compedia=array(
'labref'=>$labref, //NDQA201303001
'compedia'=>$data,
'specification'=>$data1
);
foreach ($compedia as $value) {
$this->db->insert('coa_body',$value);
}
}
When I print_r($value) it returns :
NDQA201303001
Array ( [0] => Alphy [1] => poxy [2] => alphy [3] => poxy )
Array ( [0] => poxy [1] => alphy [2] => poxy [3] => alphy )
and when I try to save, it returns:
A Database Error Occurred
Error Number: 1054
Unknown column 'NDQA201303001' in 'field list'
INSERT INTO `coa_body` (`NDQA201303001`) VALUES ('')
Filename: C:\xampp\htdocs\NQCL\system\database\DB_driver.php
Line Number: 330
How should the syntax be so as to loop over all the textarea values and save them to the database at once?

I hope that
count($data) == count($data1); //Always True!
If that's the case the following will work:
for ($i=0;$i<count($data);$i++) {
$insert_data = array(
'labref'=>$labref, //NDQA201303001 - Same for all the rows
'compedia'=>$data[$i],
'specification'=>$data1[$i]
);
$this->db->insert('coa_body',$insert_data);
}
Check this Link: CodePad.org
Update:
Suggested by Rcpayan:
//This will reduce number of context switching,
//even though loping is doubled!
for ($i=0;$i<count($data);$i++) {
$insert_data[$i] = array(
'labref'=>$labref, //NDQA201303001
'compedia'=>$data[$i],
'specification'=>$data1[$i]
);
}
$this->db->insert_batch('coa_body',$insert_data);

You could do something like this, it's a bit longer but can also deal with compedia and specification not being equal. This solutions assumes a few things:
You want the value of labref to be the same for each row inserted
If the number of values for compedia and specification aren't equal, you still want to insert the row, but the 'missing' values will be set to NULL.
$labref = $this->uri->segment(3);
$compedia_data = $this->input->post('compedia');
$specification_data = $this->input->post('specification');
//Calculate which array is larger, so we can loop through all values
$max_array_size = max(count($compedia_data), count($specification_data));
//Iterate through the arrays
for ($i = 0; $i < $max_array_size; $i++)
{
$this->db->set('labref', $labref);
//If we still have a value(s) for compedia, then assign the value, otherwise set to NULL
if array_key_exists($i, $compedia_data)
{
$this->db->set('compedia', $compedia_data[$i]);
}
else
{
$this->db->set('compedia', NULL);
}
//If we still have a value(s) for specification, then assign the value, otherwise set to NULL
if array_key_exists($i, $specification_data)
{
$this->db->set('specification', $specification_data[$i]);
}
else
{
$this->db->set('specification', NULL);
}
//Insert into table: 'coa_body'
$this->db->insert('coa_body');
}
Alternatively, you could change the loop to assign the values to an array, then batch insert these values. This might offer better performance.
//Initial other relevant code is included in the example above (excluded here for brevity)
$insert_array = new array();
//Iterate through the arrays
for ($i = 0; $i < $max_array_size; $i++)
{
$row_array = new array();
$row_array['labref'] = $labref;
//If we still have a value(s) for compedia, then assign the value, otherwise set to NULL
if array_key_exists($i, $compedia_data)
{
$row_array['compedia'] = $compedia_data[$i];
}
else
{
$row_array['compedia'] = NULL;
}
//If we still have a value(s) for specification, then assign the value, otherwise set to NULL
if array_key_exists($i, $specification_data)
{
$row_array['specification'] = $specification_data[$i];
}
else
{
$row_array['specification'] = NULL;
}
//Add current row to the insert array, so it can be added to the database
$insert_array[$i] = $row_array;
}
//Insert into table: 'coa_body'
$this->db->insert_batch('coa_body', $insert_array);

Related

How to find the keys of duplicate entries in multidimensional array

I'm reporting on appointment activity and have included a function to export the raw data behind the KPIs. This raw data is stored as a CSV and I need to check for potentially duplicate consultations that have been entered.
Each row of data is assigned a unique visit ID based on the patients ID and the appointment ID. The raw data contains 30 columns of data, the duplicate check only needs to be performed on 7 of these. I have imported the CSV and created an array as below for first record and then append rest on.
$mds = array(
$unique_visit_id => array(
$appt_date,
$dob,
$site,
$CCG,
$GP,
$appt_type,
$treatment_scheme
)
);
What I need is to scan the $mds array and return an array containing just the $unique_visit_id for any duplicate arrays.
e.g. keys 1111, 2222 and 5555 all references arrays that contain the same value for all seven values, then I would need 2222 and 5555 returned.
I've tried search but not coming up with anything that is working.
Thanks
This is what I've gone with, still validating (data set is very big) but seems to be functioning as expected so far
$handle = fopen("../reports/mds_full_export.csv", "r");
$visits = array();
while($data = fgetcsv($handle,0,',','"') !== FALSE){
$key = $data['unique_visit_id'];
$value = $data['$appt_date'].$data['$dob'].$data['$site'].$data['$CCG'].$data['$GP'].$data['$appt_type'].$data['$treatment_scheme'];
$visits[$key] = $value;
}
$visits = asort($visits);
$previous = "";
$dupes = array();
foreach($visits as $id => $visit){
if(strcmp($previous, $visit) == 0){
$dupes[] = $id;
}
$previous = $visit;
}
return $dupes;

Getting a an array from for loop and use another for loop with that array in PHP

I have a for loop, and will form two arrays in the loo
foreach ($data as $key => $value) {
........
........
$user_insert[] = [
'keyy' => $value,
'key' => $value,
....
...
...
];
$someArray1[] = [
/*'user_id' => $insert_id,*/
'key1' => $value1,
'keyy' => $value,
.......
........
];
}
the count of $user_insert[] array is 4, the count of $someArray1 is 15.
after this for loop, I need to insert $user_insert array data to the database and use that inserted_id to insert next array $someArray1
foreach($user_insert as $insert_user){
$unique_user_insert = array_unique($insert_user);
//dd($unique_user_insert);
$insert_id = DB::table('users')->insertGetId($unique_user_insert);
foreach ($someArray1 as $someArray) {
$someArray['user_id'] = $insert_id;
DB::table('table_name')->insert($someArray);
}
}
So the problem here is the data in the second loop is inserting 60 times(4 * 15). I need to insert only 15 rows.
The data($someArray1) is coming from the first for loop, but I need to add a user_id to that array which I get after the insert operation in second for loop.
So how can i insert only 15 rows.
I'm going to assume that you are able to access your $someArray1 using the $insert_id value to find the appropriate user data.
foreach($user_insert as $insert_user){
$unique_user_insert = array_unique($insert_user);
$insert_id = DB::table('users')->insertGetId($unique_user_insert);
// Get the user information you need as $someArray1 should be user_id=>data
$userData = $someArray[$insert_id];
$userData['user_id'] = $insert_id;
// No need for an inner loop, just access the necessary properties of the loop you created earlier.
DB::table('table_name')->insert($userData);
}
Your tags indicate that you are using Laravel 5 too. If you are using the eloquent ORM, some of the insertion and ID retrieval can be cleaned up by creating Models for your DB tables.
Actually, each time you process a line from $user_insert, you loop over $someArray1 instead of fetching just the line you need.
The thing is to understand the line you need. As much as I can understand your piece of code, I would say the easiest (most readable) way of doing it is by using a for loop, not a foreach one :
for( $i = 0, $iMax = count( $user_insert ); $i < $iMax; ++$i ){
$insert_user = $user_insert[$i];
// Put your `$user_insert` insert code here
$someArray1[$i]['user_id'] = $insert_id;
DB::table('table_name')->insert( $someArray[$i] ); // Note the [$i] here
}
You also may do that with foreach by requesting indices :
foreach( $user_insert as $i => $insert_user ){
$unique_user_insert = array_unique($insert_user);
//dd($unique_user_insert);
$insert_id = DB::table('users')->insertGetId($unique_user_insert);
// Now use $i requested above :
$someArray1[$i]['user_id'] = $insert_id;
DB::table( 'table_name' )->insert( $someArray1[$i] );
}

Remove null values from an array

I'm having trouble trying to remove null values from an array using values from the database. These null values are usually found within the 'answers'.. Code below:
$getQuestions = mysql_logging_query("SELECT fq.`question_id`, fq.`ques_form_id`, fq.`question_body`, fq.`type`, fq.`answer1`, fq.`answer2`, fq.`answer3`, fq.`answer4`, fq.`answer5`, fq.`answer6`, fq.`min_validation`, fq.`max_validation`
FROM QuestionnaireFormQuestions fq
LEFT JOIN QuestionnaireForms f
ON f.`form_id` = fq.`ques_form_id`
WHERE f.`active` = 1
AND f.`form_id` = '".mysql_real_escape_string($form_id,$this->dbcon)."'
",$this->dbcon);
if($getQuestions && mysql_num_rows($getQuestions)>0 && mysql_error($this->dbcon)=="")
{
$get_questions_array = array();
while($getQuestions && $getQuestions_rec=mysql_fetch_assoc($getQuestions))
{
$get_questions_array[] = array('question_id' => $getQuestions_rec['question_id'],
'related_form_id' => $getQuestions_rec['ques_form_id'],
'question_body' => $getQuestions_rec['question_body'],
'question_type' => $getQuestions_rec['type'],
'possible_answer1' => $getQuestions_rec['answer1'],
'possible_answer2' => $getQuestions_rec['answer2'],
'possible_answer3' => $getQuestions_rec['answer3'],
'possible_answer4' => $getQuestions_rec['answer4'],
'possible_answer5' => $getQuestions_rec['answer5'],
'possible_answer6' => $getQuestions_rec['answer6'],
'min_validation' => $getQuestions_rec['min_validation'],
'max_validation' => $getQuestions_rec['max_validation']
);
}
if(is_array($get_questions_array) && count($get_questions_array)>0)
{
foreach($get_questions_array as $key=>$array)
{
if($array === null) {
unset($get_questions_array[$key]);
}
$return['data']['questions'][] = $array;
}
}
}
else
//error
A return for example; would look like this:
"question_id":"3",
"related_form_id":"4",
"question_body":"Do you like this content?",
"question_type":"radio",
"possible_answer1":"Disagree",
"possible_answer2":"Neutral",
"possible_answer3":"Agree",
"possible_answer4":null,
"possible_answer5":null,
"possible_answer6":null,
"min_validation":"1",
"max_validation":"1"
I've tried unsetting the key using empty and isnull but to no avail. Any help would be appreciated.
You are not testing the values inside the array, you need to:
foreach($get_questions_array as $array){
foreach($array as $key=>$element){
if($element===null)
unset($array[$key]);
}
$return['data']['questions'][] = $array;
}
I think it's possible you're looping through your nested data structure at the wrong level.
You have this $get_questions_array, each element of which is an associative array that came from one row in your MySQL result set. But your php code loops over the rows of the result set, not over the columns.
I think you want something more like this, with another nested foreach.
if(is_array($get_questions_array) && count($get_questions_array)>0)
{
foreach($get_questions_array as $row)
{
foreach ($row AS $colname=>$colvalue)
{
if ($colvalue === null || $colvalue =='')
{
unset($row[$colname]);
}
}
}
}
See what's going on? Your code was throwing away whole rows that were null, but there weren't any of those, so it wasn't doing anything.
why don't you query the data that does not contain nulls, instead of removing the nulls by yourself ? let the database do this for you something like:
select * from table where possible_answer IS NOT NULL
Try this loop through the array and set them to null with the key's if the value is empty
foreach($getQuestions_rec as $key => $value){
if($value == ''){
$getQuestions_rec[$key] = null;
}
}
Use the IFNULL(ColumnName,"") to replace the null values to empty string in SQL query.
Example: IFNULL(answer6,"")
refer this this How to remove null values from an array? or you ca alter the query to select the null values from table.

Create Array and print it into TXT file

UPDATE:
I get array values from $_POST['changed'].
The array structure looks like this:
Array
(
[0] => Array
(
[recid] => 1
[nachname] => Müller7777
)
[1] => Array
(
[recid] => 3
[vorname] => Maria123
)
)
I get on line #3 this error: Fatal error: Function name must be a string
$uarr=array();
foreach ($_POST['changed'] as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
$uarr[$y][]="$k='$v'";
}
foreach ($uarr as $k=>$v) {
$sql = "";
$sql .="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
file_put_contents('filename2.txt', $sql);
Before I do the final database UPDATE I want to check if the created array does its job. Thats why I want to write the $sql variable first into a txt-file.
------------------------------------------------
SOLUTION:
checking if $_POST['changed'] == null is the final answer for this question.
if ($_POST['changed'] == null) {
} else {
$uarr=array();
$b = $_POST['changed'];
foreach ($b as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
// $x contains the `recid` key
// $y ... value
$uarr[$y][]="$k='$v'";
}
foreach ($uarr as $k=>$v) {
$sql = "";
$sql .="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
file_put_contents('filename2.txt', $sql);
}
Before you run the individual UPDATE statements - yes, for each recid value you should send one statement - you could first collect all the affected values for each recid in an associative array like
$uarr=array();
foreach ($_POST['changed'] as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
// $x contains the `recid` key
// $y ... value
$uarr[$y][]="$k='$v'";
}
and then do another loop like
foreach ($uarr as $k=>$v) {
$sql="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
But, of course, this will only work correctly if the $_POST('changed') array adheres to the described format and order. And, finally, so far there is nothing in this code to protect you from SQL injection.
Try to do it like this:
$BigArray = $_POST['changed'];
$LengthOfArray = sizeof($BigArray);
for ($i = 0; $i < $LengthOfArray ; $i++) {
$SubArray = $BigArray[$i];
// Call the update/insert here
// $SubArray['recid'] is the ID
// $SubArray['vorname'] is the name
}

adding elements in an array day-wise from mysql database

How can I get the record values in the database to be sorted like this in an array. Supose I am adding the day no.
array
[0] => array=>'id'=>'26' 'date'=>'26'
[1] => array=>'id'=>'27' 'date'=>'27',
array=>'id'=>'28' 'date'=>'27',
array=>'id'=>'29' 'date'=>'27'
[2] => array=>'id'=>'30' 'date'=>'29'
[3] => array=>'id'=>'31' 'date'=>'31',
array=>'id'=>'32' 'date'=>'31',
array=>'id'=>'33' 'date'=>'31'
Basically, I want to add an array to the same index if the next id contains a record with the same date (day no) of the month. Otherwise add it normally.
Right now, My function is adding the rows of the record without sorting it in the format I want it to be in.
The reason I want it to be in this format is because, I need to run the foreach, and if 1 day contains 2 records, then it will append another <li> into my unordered list.
public function getArticles()
{
$sql = 'CALL getArticles()';
$articles = Array();
if (Model::getConnection()->multi_query($sql)) {
do {
if ($result = Model::getConnection()->store_result()) {
while ($row = $result->fetch_assoc()) {
array_push($articles,$row);
}
$result->free();
}
} while (Model::getConnection()->next_result());
}
return $articles;
}
I don't recognize what some of your code is doing, but I think this is the important part.
while ($row = $result->fetch_assoc()) {
if (!isset($articles[$row['date']])) {
$articles[$row['date']] = array();
}
$articles[$row['date']][] = $row;
}
The only difference will be that your array will be keyed on the date instead of incrementing from zero. If you really want it reindexed, you can do...
array_values($articles);
As savinger pointed out, there is alot of functionality in your code which I don't really know, so I've included comments to indicate whereabouts the process is:
// Start of your loop
// $value is what you're getting from the DB...
$array_search = array_search($value,$main_array);
if($array_search)
{
// If this value already exists, we need to add
// this value in +1 of its current value
$main_array[$array_search][] = $value + 1;
}
else
{
// Make a new array key and add in the value
$main_array[] = $value;
}
// End of your loop

Categories