PHP Dynamic insert by multidimensional array - php

Array (
[modo_prep] =>
[modo_serv] =>
[id_prod_comp] => 18
[id_ingrediente] =>
Array (
[0] => 16
[1] => 17
[2] => 18
)
[qtd] => Array (
[0] => 10
[1] => 100
[2] => 1000
)
[rend_kg] => Array (
[0] => 20
[1] => 200
[2] => 2000
)
[submit] => Guardar
[id_receita] => 0
)
(post array) and need to be dynamic insert, so i want to do a universal post function to insert.
with simple array its ok 2 dimensoions there is a problem because i cannot match 1st value of N and so on, i need to be each array but same position each one sub-arrays to put in insert sentence.
so example: i have 1 row product, dinamic jquery (id_product[]) and i dont want to put the keys i want the script read all post data and put simple array in one table and the other N in other mysql table and each loop create 1 record with same key of each N sub arrays. row 1 has 3 fields it comes with 3 arrays, each row but if i put N i need to deal with that.
Code:
<?
ERROR_REPORTING(E_ERROR);
if($_POST['submit'] == TRUE){
$table = 'receitas';
$table2 = 'receitas_componentes';
$element1 = array();
$element3 = array();
$i=0;
foreach ($_POST as $key =>$valor){
if( $key != 'submit'){
if( !is_array($valor )){
$element1[$key] = $valor;
$colnames = "`".implode("`, `", array_keys($element1))."`";
$colvals = "'".implode("', '", $element1)."'";
$query_element1="INSERT INTO `".$table."` (".$colnames.") VALUES (".$colvals.")";
}else{
//echo $colvals = "'".implode("', '", $element1)."'";
$count = sizeof($valor);
extract_1_array($valor,0);
//else
}
//not submit
}
}
//echo $query_element1;
//mysql_query($query_element1);
$id_receita= mysql_insert_id();
//$_POST['id_receita']=$id_receita;
}
function extract_1_array($valor, $increment){
$i=0;
foreach ($valor as $key2 => $ingredientes){
$subarray[$i] .=$ingredientes ;
$i++;
}
echo $subarray[$i]; echo("<br>");
//$var10= implode($subarray[0]);
}
//echo $var10;
?>
<br><br><br><br><br><br><br><br>
blank

Related

How to get all values inside multidimensional array in PHP

I am working on online TV series website and can't figure out this one need to get values from array which is inside array.
This is structure contains $seasons variable:
Array
(
[0] => Array
(
[0] => link1-1
[1] => link1-2
[2] => link1-3
)
[1] => Array
(
[0] => link2-1
[1] => link2-2
[2] => link2-3
)
)
i need to get values like:
0
link1-1
link1-2
link1-3
1
link2-1
link2-2
link2-3
and then put them inside html video tag, but i can't figure out how to get values correctly
tried:
while ($row = $result->fetch_assoc()) {
$season_count = $row['season_count'];
$seasons = array_map("str_getcsv", explode("___", $row['en_url']));
array_shift($seasons);
for($i = 0; $i < count($seasons); $i++){
print_r($seasons[$i][*]); // i need equivalent of * to select all values of each array
}
break;
}
foreach ($seasons as $season){
foreach ($season as $link) {
echo '<video src="' . $link . '"><video>';
}
}
And next time - please formulate your task clearly.

Looping through array and get non-repeating values

I have an array of elements which I queried from the mongoDB.
This array has the id of a device and value of this device's consumptions.
For example there are 3 different ids -> 18,5,3 and multiple mixed values.
// first record of 18 so get value.
$row[0]["id"] = 18;
$row[0]["value"] = 100;
// not first record of 18 so ignore and move to the next record
$row[1]["id"] = 18;
$row[1]["value"] = 40;
// first record of 5 so get value.
$row[2]["id"] = 5;
$row[2]["value"] = 20;
// not first record of 18 so ignore and move to the next record
$row[3]["id"] = 18;
$row[3]["value"] = 30;
// first record of 3 so get value.
$row[4]["id"] = 3;
$row[4]["value"] = 20;
//not first record of 5 so ignore and move to the next record**
$row[5]["id"] = 5;
$row[5]["value"] = 30;
// not first record of 18 so ignore and move to the next record
$row[6]["id"] = 18;
$row[6]["value"] = 10;
...
....
What I am trying to do is loop through this $row array and get the most recent value of the id.
For example in above example what I want to return is:
id value
18 100
5 20
3 20
How can I do that kind of logic?
It can be done in several ways. The easiest one is to use a foreach:
$result = array();
foreach ($row as $i) {
if (! array_key_exists($i['id'], $result)) {
$result[$i['id']] = $i['value'];
}
}
# Verify the result
print_r($result);
The output is:
Array
(
[18] => 100
[5] => 20
[3] => 20
)
The same processing, but using array_reduce():
$result = array_reduce(
$row,
function(array $c, array $i) {
if (! array_key_exists($i['id'], $c)) {
$c[$i['id']] = $i['value'];
}
return $c;
},
array()
);
If you want to keep only the first occurrence of each 'id' then just add the values to an aggregate array - but only if they haven't been added already. Then grab the values of the aggregate array.
https://tehplayground.com/NRvw9uJF615oeh6C - press Ctrl+Enter to run
$results = array();
foreach ($row as $r) {
$id = $r['id'];
if (! array_key_exists($id, $results)) {
$results[$id] = $r;
}
}
$results = array_values($results);
print_r($results);
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
Try this
$alreadyfound = []; // empty array
$result = [];
foreach ($row as $item)
{
if (in_array($item["id"], $alreadyfound))
continue;
$alreadyfound[] = $item["id"]; // add to array
$result[] = $item;
}
The result
Array
(
[0] => Array
(
[id] => 18
[value] => 100
)
[1] => Array
(
[id] => 5
[value] => 20
)
[2] => Array
(
[id] => 3
[value] => 20
)
)
The array_unique() function is exactly what you are looking at.
See the documentation here : array_unique() documentation
Using array_column with an index key will almost do it, but it will be in the reverse order, so you can reverse the input so that it works.
$result = array_column(array_reverse($row), 'value', 'id');

How to insert multiple dynamic rows into the database

I have a multiple row dynamic table that I created using php and jQuery. Here's the link to view the table.
Everything is working fine except when I insert the data into the database, the serial numbers do not save sequentially. My insert queries are as below:
for($i = 0; $i < count($_POST['C_Objectives']); $i++)
{
$sql = "INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,Measures,Targets,subtotal,Corporate_Objective,Row_Number,ID) Values ('$formno','||<==','==','==','".$_POST['SubTotals'][$i]."','".$_POST['C_Objectives'][$i]."','".$_POST['SNo'][$i]."','$statement')";
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false)
die(print_r(sqlsrv_errors(), true));
else
echo " ";
}
for($i = 0; $i < count($_POST['Measures']); $i++)
{
$sql = "INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,Measures,Targets,Weightage,Row_Number,target_date,ID) VALUES ('$formno','".$_POST['Objectives'][$i]."','".$_POST['Measures'][$i]."','".$_POST['Achievement'][$i]."','".$_POST['Weightage_Target'][$i]."','".$_POST['SNo'][$i]."','".$_POST['Date_Target'][$i]."','$statement')";
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false)
die(print_r(sqlsrv_errors(), true));
else
echo " ";
}
The serial number is saved in the column Row_Number, using $_POST['SNo'][$i]. Is it possible to save both of the dynamic rows using 1 insert query so that the serial numbers are saved sequentially?
This is the $_POST array result:
[Row_Number] => Array
(
[0] => 1
[1] => 2
)
[C_Objectives] => Array
(
[0] => A
[1] => B
)
[Objectives] => Array
(
[0] => a1
[1] => a4
[2] => a7
[3] => b1
)
[Measures] => Array
(
[0] => a2
[1] => a5
[2] => a8
[3] => b2
)
[Achievement] => Array
(
[0] => a3
[1] => a6
[2] => a9
[3] => b3
)
[Date_Target] => Array
(
[0] => 2016-09-09
[1] => 2016-09-09
[2] => 2016-09-09
[3] => 2016-09-09
)
[Weightage_Target] => Array
(
[0] => 25
[1] => 25
[2] => 25
[3] => 25
)
[SNo] => Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
)
[SubTotals] => Array
(
[0] => 75
[1] => 25
)
[GrandTotal] => 100
)
I've also tried making the column auto-increment, but yet doesn't save the data in the same order as it is entered in the front end.
Your inserting has performance issue. Please change your way for inserting to the database. You can do all of them in one query. Even if you have 20 loop for first "for" and 20 loop for 2nd "for".
Answer to What you asked
If you want to insert by $_POST['SNo'] order, change this line
for($i = 0; $i < count($_POST['C_Objectives']); $i++)
to the
foreach($_POST['SNo'] as $i)
If you need multiple insert at once, just do this:
INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,...)
VALUES (Value1,Value2,...), (Value1,Value2,...)
This is What you MUST do
In your code, you did the same query in 6 queries. It can even be more than 6 with more $_POST['Measures'] or $_POST['C_Objectives'] array length.
You need to Put them in one query and when you don't need to set the value, just set it to the column default value. for example NULL
Something like this:
//first we create $values array. it contains all values that you need to insert to the db
$values = array();
$j=0;
for($i = 0; $i < count($_POST['C_Objectives']); $i++){
$values[$j]['Serial_Number'] = $formno;
$values[$j]['Objectives'] = '||<==';
//and fill others here
//fill all cols that you wrote inside your query with the correct order
$j++;
}
for($i = 0; $i < count($_POST['Measures']); $i++){
$values[$j]['Serial_Number'] = $formno;
$values[$j]['Objectives'] = $_POST['Objectives'][$i];
//and fill others here
//fill all cols that you wrote inside your query with the correct order
$j++;
}
//now create (value1,value2,...),(value1,value2,...),...
$query = NULL;
foreach($values as $value){
$tmp = NULL;
foreach($value as $v){
$tmp .= ($v=='')? 'NULL,' : "'$v',";
}
$tmp = rtrim($tmp,',');
$query .= "($tmp),";
}
$query = rtrim($query,',');
//Now Insert
$sql = "INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,...) VALUES $query";
In this example I just showed you how to do it. Remember, you must check $v and prepare it by your column type. check if $_POST[KEY] is set and it's array. Don't insert to the database if $query is empty.
Very Important about your codes
If this is not your original code there is no problem but if it is, please change the way you are using $_POST inside your query. It has very low security. at least you need to validate them before using it.
Yes you can able to insert in single insert query.
$arrMeasuresInsData = array();
for($i = 0; $i < count($_POST['C_Objectives']); $i++) {
$sql = "INSERT INTO Appraisal_Objectives (Serial_Number, Objectives, Measures, Targets, subtotal, Corporate_Objective, Row_Number, ID, Weightagen, target_date)
Values ('$formno',
'||<==',
'==',
'==',
'".$_POST['SubTotals'][$i]."',
'".$_POST['C_Objectives'][$i]."',
'".$_POST['SNo'][$i]."',
'$statement',
'',
'')";
if(!empty($_POST['Measures'][$i])) {
$arrMeasuresInsData[$i] = $_POST['Measures'][$i];
$sql .= ",('$formno',
'".$_POST['Objectives'][$i]."',
'".$_POST['Measures'][$i]."',
'".$_POST['Achievement'][$i]."',
'',
'',
'".$_POST['SNo'][$i]."',
'".$_POST['Date_Target'][$i]."',
'".$_POST['Weightage_Target'][$i]."',
'$statement',)";
}
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false)
{
die(print_r(sqlsrv_errors(), true));
}
else
{
echo " ";
}
}
for($i = 0; $i < count($_POST['Measures']); $i++) {
if(isset($arrMeasuresInsData[$i])) {
continue;
}
$sql="INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,Measures,Targets,Weightage,Row_Number,target_date,ID)
VALUES ('$formno',
'".$_POST['Objectives'][$i]."',
'".$_POST['Measures'][$i]."',
'".$_POST['Achievement'][$i]."',
'".$_POST['Weightage_Target'][$i]."',
'".$_POST['SNo'][$i]."',
'".$_POST['Date_Target'][$i]."',
'$statement')";
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false)
{
die(print_r(sqlsrv_errors(), true));
}
else
{
echo " ";
}
}
I think you are getting your $_POST array wrongly. You have to change the input form and recieve the input some thing like below:
[C_Objectives] => Array
(
[Row_Number] => Array
(
[title] => 'xxx',
[0] => Array
(
[0] => Array
(
[SNo] => 2
[Objectives] => a1,
[Measures] => a2,
[Achievement] => a3,
[Date_Target] => 2016-09-09,
[Weightage_Target] => 25
),
(
[SNo] => 3
[Objectives] => a1,
[Measures] => a2,
[Achievement] => a3,
[Date_Target] => 2016-09-09,
[Weightage_Target] => 25
),
(
[SNo] => 4
[Objectives] => a1,
[Measures] => a2,
[Achievement] => a3,
[Date_Target] => 2016-09-09,
[Weightage_Target] => 25
),
[SubTotals] => 75
)
)
},
(
[Row_Number] => Array
(
[title] => 'xxx',
[0] => Array
(
[0] => Array
(
[SNo] => 6
[Objectives] => a1,
[Measures] => a2,
[Achievement] => a3,
[Date_Target] => 2016-09-09,
[Weightage_Target] => 25
),
[SubTotals] => 25
)
)
)
Above is the only example rest you have to understand how to do that.
As it would be difficlut to know which value belong to which row it might be possible that value defined as 2nd below to 3rd row.
With the current code, there will be at least two INSERT statements, and more when $_POST['Measures'] or $_POST['C_Objectives'] contain a larger number of elements.
You can insert multiple records with one statement, and instead of using a for statement, use a foreach so you don't have to do the bookkeeping on the iterator variable. Then store values in arrays and use implode() to combine the sets of values for each record.
Check which values are being inserted into which columns - it appears that in the first for loop of your example, you are inserting the value from $_POST['SNo'][$i] into the ID field...
$values = array();
foreach($_POST['C_Objectives'] as $index=>$value) {
$rowValues = array();
$rowValues[] = $_POST['SNo'][$index]; //Serial_Number
array_push($rowValues,$formno,'||<==','==','=='); //, Objectives, Measures, Targets, subtotal
$rowValues[] = $_POST['SubTotals'][$index]; //Corporate_Objective
$rowValues[] = $value; //Row_Number: $value == $_POST['C_Objectives'][$index];
$values[] = "('".implode("', '",$rowValues )."')";
}
$fields = array('Objectives','Measures','Achievement','Weightage_Target','SNo','Date_Target');
foreach($_POST['Measures'] as $index=>$value) {
$rowValues = array($formno);
foreach($fields as $field) {
$rowValues[] = $_POST[$field][$index];
}
$values[] = "('".implode("', '",$rowValues )."')";
}
$sql = "INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,Measures,Targets,subtotal,Corporate_Objective,Row_Number,ID) VALUES ".implode(', ',$values);
$stmt = sqlsrv_query($conn, $sql);
if($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
else {
echo " ";
}
what are you going to do? Two loop execution is different insertion .....
Solution:
1. The second update operation.
2. organize the data into the database at once.

Display value of two-dimensional php array in table

I've got an array extracted from MySQL called "$agents", looking like:
Array (
[0] => Array ( [agent] => Agent/1002 [total] => 02:11:07 )
[1] => Array ( [agent] => Agent/1400 [total] => 01:49:53 )
[2] => Array ( [agent] => Agent/1500 [total] => 03:26:29 ) )
Then another MySQL query creates a table as:
while ($row = mysql_fetch_row($q)) {
$result .="<tr><td>".$row[0]."</td><td align=center>".
$row[1]."</td><td align=center>".
$row[2]."</td><td align=center>".
$row[3]."</td><td align=center>".$agents['0']['total']."</tr>";
}
How can I get the 'total' value from the array displayed in the last column of the table?
I want to insert the total for each agent. With an if statement, very simplified, like:
if $row[0] == $agents['0']['agent'] echo $agents['0']['total'] else echo 'NONE'"
Tried with "foreach" loop, but didn't get it to work.
Any ideas/suggestions of how this can be done?
You could initialize a counter above the second fetching. Like this:
$agents = holds your first data fetches from db
$i = 0; // initialize a counter
while ($row = mysql_fetch_row($q)) {
// condition block
if($row[0] == $agents[$i]['agent']) {
$total = $agents[$i]['total']; // if they match, assign the total
} else {
$total = ''; // else just assign an empty string
}
$result .="
<tr><td>".$row[0]."</td>
<td align=center>".$row[1]."</td>
<td align=center>".$row[2]."</td><td align=center>".$row[3]."</td>
<td align=center>".$total."</tr>
";
$i++; // increment
}

How to group the result of array in two categories in PHP?

I have data here:
Array
(
[1] => Array
(
[SiteID] => 1
[OwnerAID] => 1
)
[3] => Array
(
[SiteID] => 3
[OwnerAID] => 1
)
[6] => Array
(
[SiteID] => 6
[OwnerAID] => 2
)
)
Now, I need to group the OwnerAID into two categories: the first one is OwnerAID owning only one SiteID and the second one is OwnerAID owning more than 1 SiteID.
I've tried to make a program and do some research, but the output of my code is wrong.
Please see my code:
public function groupIndividualAndAggregateSites()
{
$arrays = array();
foreach($this->combined as $key => $key_value)
{
$SiteID = "";
if ($SiteID == "") {
$SiteID=array($key_value['SiteID']); }
else {
$SiteID = array_merge((array)$SiteID, (array)$key_value['SiteID']);
$SiteID = array_unique($SiteID);
}
} if ($SiteID != "") {
$arrays = array('AID'=>$key_value['AID'], 'Sites' => $SiteID);
}
print_r($arrays);
}
The result should be shown like this:
Array(
[1] => Array
( [Sites] => Array ([0] => 1, [1] => 3)))
Array(
[2] => Array
( [Sites] => Array ([0] => [6]))
What you should go for is array:
$owners = array(
owner_1 => SiteID1, // int Only one site
owner_2 => array (SiteID2,SiteID3), // array Multiple sites
);
and later use the array $owners like:
echo (is_array($owners[$owner_1]) ? 'Has multiple sites' : 'has one site';
Thats the basic idea of small memory footprint.
Example, not tested.
public function groupIndividualAndAggregateSites() {
$owners = array();
foreach($this->combined as $key => $value) {
$owner_id = $value['OwnerAID'];
$site_id = $value['SiteID'];
if(array_key_exists($owner_id,$owners)) {
// He has one or more sites already?
if(is_array($owners[$owner_id]){
array_push($owners[$owner_id],$site_id);
} else {
// User already has one site. Lets make an array instead and add old and new siteID
$old_site_id = $owners[$owner_id];
$owners[$owner_id] = array($old_site_id,$owner_id);
}
} else {
$owners[$owner_id] = $site_id;
}
return $owners;
}
All you need to do is loop over your initial array, appending each OwnerAID to the relevant output subarray as determined by the SiteID:
$output = array(1=>array(), 2=>array());
foreach ($original as $v) $output[$v['SiteID'] == 1 ? 1 : 2][] = $v['OwnerAID'];
Here I am using the following features:
array() initialisation function;
foreach control structure;
ternary operator;
$array[$key] addressing;
$array[] pushing.

Categories