AJAX foreach $_POST merge values - php

I'm gonna try to be as clear as possible.
I'm currently working on a project for my work, with dynamic forms where the form inputs are in a database, and created dynamically. Every input row looks something like:
Question? Radiogroup Textinput
And when the user press submit in a section of maybe 3-5 of these rows the form is serialised and managed with AJAX. So here comes the part I'm having trouble with, as of now, in my AJAX file, there is a foreach loop which loops through all $_POST values, adds them to an array and then after the array is complete all data is inserted to a SQL database. And I don't know if it's a problem since I'm not a professional DBA, but there's a lot of rows being inserted to the database, since EVERY radio group, and EVERY text input, gets their own row. And I was thinking if I at least could cut it down to every question getting their own row, but how do I then merge the radio group value with the text input value so they are on the same row but different columns.
I hope I'm being clear enough here.
Database layout today
|ID|RowID|Type|User|Value
Where Type is either Radio or Text. What I want to achieve to get half of the rows I'm gonna get this way is:
|ID|RowID|Type|User|Radio|Text
And the problem is howto achieve this when my foreach loop fills an array with a lot of rows, for each form, which as I say, is containing maybe 3-5 rows with both a radio group and a text input. This is how I do it today:
foreach($_POST as $key => $value) {
$values[] = "'{$id}', '{$user}', '{$type}', '{$value}'";
}
$mysqli->query('INSERT INTO data (rowid, user, type, value) VALUES ('.implode('),(', $values).')');
Hope someone can help me out.
Best Regards
Cisco

Solved it by doing the following:
//Only define for testing.
$_POST['rad_1'] = "yes";
$_POST['rad_2'] = "no";
$_POST['rad_3'] = "yes";
$_POST['txt_1'] = "Test";
$_POST['txt_2'] = "Test2";
$_POST['txt_3'] = "Test3";
$array = array();
foreach($_POST as $key => $value) {
$keyarr = explode('_', $key);
$type = $keyarr[0];
$id = $keyarr[1];
$value = $value;
$array[$id][$type] = $value;
}
$values = array();
foreach($array as $key => $value)
{
$values[] = implode(', ', $value);
}
$query = "INSERT INTO table_name test VALUES (" . implode ("),(", $values) . ")";

Related

How to stop second foreach from looping more than once

I have an query which select all ids from a table. Once I have all id's, they are stored in an array which I foreach over.
Then there is an second array which pull data from url (around 5k rows) and should update DB based on the id's.
The problem - second foreach is looping once for each ID, which is not what I want. What I want is to loop once for all id's.
Here is the code I have so far
$query = " SELECT id, code FROM `countries` WHERE type = 1";
$result = $DB->query($query);
$url = "https://api.gov/v2/data?api_key=xxxxx";
$api_responce = file_get_contents($url);
$api_responce = json_decode($api_responce);
$data_array = $api_responce->data;
$rows = Array();
while($row = $DB->fetch_object($result)) $rows[] = $row;
foreach ($rows as $row) {
foreach ($data_array as $key => $dataArr) {
$query = "UPDATE table SET data_field = $dataArr->value WHERE country_id = $row->id LIMIT 1";
}
}
The query returns 200 id's and because of than the second foreach (foreach ($data_array as $key => $dataArr) { ... }) execute everything 200 times.
It must execute once for all 200 id's not 200 * 5000 times.
Since the question is aboot using a loop, we will talk about the loop, instead of trying to find another way. Actually, I see no reason to find another way.
->Loops and recursions are great, powerful tools. As usually, with great tools, you need to also find ways of controlling them.
See cars for example, they have breaks.
The solution is not to be slow and sit to horses era, but to have good brakes.
->In the same spirit, all you need to master the power called recursions and loops is to stop them properly. You can use if cases and "break" command in PHP.
For example, here we have a case of arrays containing arrays, each first child of the array having the last of the other (1,2,3), (3,4,5) and we want to controll the loop in a way of showing data in a proper way (1,2,3,4,5).
We will use an if case and a counter :
<?php
$array = array( array(-1,0,1), array(1,2,3,4,5), array(5,6,7,8,9,10), array(10,11,12,13,14,15) );
static $key_counter;
foreach( $array as $key ){
$key_counter = 0;
foreach( $key as $key2 ){
if ( $key_counter != 0 ) {
echo $key2 . ', ';
}
$key_counter = $key_counter + 1;
}
}
Since I dont have access to your DB is actually hard for me to run and debbug the code, so the best I can say is that you need to use an if case which checks if the ID of the object is the ID we want to proccess, then proceed to proccessing.
P.S. Static variables are usefull for loops and specially for recurrsions, since they dont get deleted from the memory once the functions execution ends.
The static keyword is also used to declare variables in a function
which keep their value after the function has ended.

How to split array by 3 php

Problem
I have a form table with multiple textbox and one submit button
Im using implode but all value's are inserted in array
$val = implode(',',$textboxval);
result is (80,80,80,40,80,90,70,70,70)
What i want is i want to insert each row of data's in an group of array in the database
[0]=(80,80,80),1=(40,80,90),2=(70,70,70)
RESULT
You could use array_chunk:
foreach (array_chunk($textboxval, 3) as $values) {
$val = implode(',', $values);
// insert $val into database
}

PDO update query pushes submit input value on all columns

I have a PDO update query gets the $_POST (or any other key-value array) and writes up the UPDATE query in respect to the inputs given.
I have an exclude array that I can specify keys to not include in the SQL query, such as the submit key and value of the form (action_update_survey, in this case.).
I create the SQL query by iterating through the array via foreach to firstly create the query and insert the parameter placeholders and secondly to bind the parameters to the parameter placeholder within the query.
Here is my code:
function save_survey($post){
global $pdo;
$exclude_names = array('action_update_survey');
$wp_userid = get_current_user_id();
$update_survey_query = "UPDATE kwc_surveysessions SET ";
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)) $update_survey_query .= $key." = :".$key.", ";
}
$update_survey_query = rtrim($update_survey_query, ", ")." WHERE wp_userid=:wp_userid";
$update_survey = $pdo->prepare($update_survey_query);
print_r($update_survey_query);
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)){
$update_survey->bindParam($key, $value);
}
}
$update_survey->bindParam("wp_userid", $wp_userid);
$update_survey->execute();
}
After executing my function following a post, all text columns in my database are set to the value 'Save', which is the value of the submit input, of name *action_update_survey*, which is strange, because it should be excluded from both foreach loops, which assign the keys and values.
Printing the PDO query before executing shows that there's been no setting of the excluded input anywhere in my query:
UPDATE kwc_surveysessions SET s1q1 = :s1q1, s1q2 = :s1q2, s1q7 = :s1q7, s1q8 = :s1q8, s1q9 = :s1q9, s1q10 = :s1q10, s1q11 = :s1q11, s2q6 = :s2q6, s3q7 = :s3q7 WHERE wp_userid=:wp_userid
Any idea what would be causing the submit input to push its value into all my fields?
The most probable cause is that bindParam() passes values by refference.
Try using an array like this:
arr = array();
foreach($post as $key=>$value){
if(!in_array($key, $exclude_names)){
arr[$key] = $value;
}
}
$update_survey->execute($arr);
and use "arr" to execute the query.

PHP, SQL, in_array with csv and while loop only retrieving integer

I have searched for similar questions but cannot find the right answer to my specific one. I have a column (data) in my table (table) which contains comma separated values which are id's e.g.
Row 1= 4,5,45
Row 2= 5,8,9
Row 3= 5
I use an in_array function to retrieve the number of occurances for the $data value within the while loop. So I use an sql function to retrieve the number of times a certain value such as '5' occurs in all rows within the while loop.
The issue is that I can only retrieve the $data value if it is by itself (i.e. no commas just the integer by itself) so based on my example in the list, I can only retrieve 5 once (row 3). I would like to retrieve the value '5' three times as it appears in all the rows. Here is my code below and any help would be appreciated. The $selectiontext variable is what the user enters from the form.
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
}
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
Thank you.
you keep overwriting the variables $datacheck and $id, leaving you with only the last version of them. move that curly brace down two lines, like this:
$sql_frnd_arry_mem1 = mysql_query("SELECT data, id FROM table WHERE data='$selectiontext'");
while($row=mysql_fetch_array($sql_frnd_arry_mem1)) {
$datacheck = $row["data"];
$id = $row["id"];
$frndArryMem1 = explode(",", $frnd_arry_mem1);
if (($frnd_arry_mem1 !=="") && (!in_array($id, $frndArryMem1))) {echo $id;}
}
I am not totally sure of your requirements, is not very clear what you intend to do as part of the code is missing.
I assume you want to check each row of a comma separated of a CSV file ($frnd_arry_mem1 being the row) against your data in column data, if any of those comma separated data (not) occurs.
Assuming you are already looping through your CSV, this would be the code (non tested):
NOTE: might be inefficient retrieving data within a loop, if you can do otherwise - but I cant tell as I dont kow the full specs of your script.
If I got the specs wrong please clarify, I will try to help further.
$sql = "SELECT data, id
FROM table
WHERE data='$selectiontext'";
$sql_frnd_arry_mem1 = mysql_query($sql);
$results = array();
// get values to check
while ($row = mysql_fetch_array($sql_frnd_arry_mem1))
{
$results[] = array(
'datacheck' => $row["data"],
'id' => $row["id"],
);
}
foreach ($results as $result)
{
$frndArryMem1 = explode(",", $frnd_arry_mem1);
$data = explode(',', $result['datacheck']);
foreach ($data as $d)
{
if (($frnd_arry_mem1 !=="") && (!in_array($d, $frndArryMem1)))
{
echo 'DEBUG: Record #' . $id . ' not found, value:' . $d . '</br>';
}
}
}

PHP Array Explode

I am imploding data inside of an array, called the following:
["Levels_SanctionLevel_array"]=>
string(14) "IR01,IR02,IR03"
I need to explode this data and input each value as a row inside of mysql. Such as
pri_id value
---------------
01 IR01
02 IR02
03 IR04
Now where I am getting stuck is this:
The array listed above could have 1 value, 3 values (right now I am showing three values) or 5 values, and I dont want to input NULL values inside of my database.
Appreciate any guidance anyone can share...
$data = explode(',',$your_string);
foreach ($data AS $value) {
// INSERT INTO DB
}
A simple loop works correctly, but has the drawback of making multiple queries to the database:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
foreach ($vals AS $value) {
// insert into database
}
As DB operations are a more significant bottleneck than building a query in PHP, I would opt to generate the SQL code for a single query as follows:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
$query = 'INSERT INTO my_data VALUES ';
foreach ($vals as $value) {
$query .= "('', '".$value."'),";
}
$query = rtrim($query, ',');
// insert into database
Why don't you use an iterator over the array to construct the sql query? That way you will only insert as many elements as you have in the array.
Like the answer above. I think we were answering at the same time.
Supposing your major array is $data:
foreach ($data as $values)
{
$value = explode(",", $values);
foreach ($value as $v)
{
$sql = "INSERT INTO table(value) VALUES('$v')";
}
}

Categories