PHP MySQL insert multimensional associative array building query from array keys [duplicate] - javascript

This question already has answers here:
INSERT array - PDO
(2 answers)
Binding values from arrays?
(3 answers)
Closed 5 years ago.
I have tried both the links but I don't get the expected variables content in $fields and $newdata
** This question has developed in a new one here **
PHP how to extract keys names and values from associative array for mysql query (as explained I'm newbie and it took some work to get the question asked in the right way)
so I kindly print here some var_dump and cast to kindly ask your support.
For simplicity in my learning experiment, I'm working with a dummy table of just 5 fields, as you see they are: selected, user_id, user_name, user_company and user_email.
Finally I have inserted just 2 rows of values.
Using this code
$Arr = (array)$data;
print_r ( $Arr );
I can see this output
Array (
[0] => Array ( [selected] => [user_id] => 3 [user_name] => nome3 [user_company] => azien3 [user_email] => email3 )
[1] => Array ( [selected] => 1 [user_id] => 6 [user_name] => nome6 [user_company] => azien6 [user_email] => email6 )
)
next I try to apply the code of your links
24 $fields = implode(",", array_keys($Arr));
25 $newdata = "'" . implode("','", $Arr) . "'";
26
27 var_dump($fields);
28 echo "<br><br>";
29 var_dump($newdata);
But something is wrong in my interpreteation or in my code , because the output is
Notice: Array to string conversion in D:\xampp\htdocs\ajax-json\post.php on line 25
Notice: Array to string conversion in D:\xampp\htdocs\ajax-json\post.php on line 25
string(3) "0,1"
string(15) "'Array','Array'"
can you kindly point out what's wrong?
e.g. is my array properly formed?
ORIGINAL QUESTION
I'm newbie and after further readings I got the point and hopefully now my question could result more simple. Thank you for any hint.
I have a bidimensional array since its records are coming from an html table.
The collection made on the html side generates an associative array so each row is like in the following example where, also, you can see, the keys are many
[item] => Array (
[0] => Array (
[unit] => "car"
[qty] => 3
[description] => "Description 1"
....
[key47] => "thin"
)
[1] => Array (
[unit] => "bike"
[qty] => 74
[description] => "Description 2"
....
[key47] => "large"
)
)
The mysql table name where I want to insert the items is named items_table
"unit" "qty" and "description" and all the remaining keys (total 47) are exactly the same names of the items_table columns
When on the php side I'd like to have a sort of automatic query generation maybe with PDO that would pick the columns names from the inner array keys names and will insert the corresponding key value in the correct column.
The goal is to avoid creating such a awkward and extremely long query.
Preferred method would be with PDO, avoid binding 47 keys.
This sort of automatism is also useful because in the future columns in the mysql table may being added and or removed and or renamed, so I'd like to forget about the query thinking only about properly editing the html table (on that side the array is already automatically generated with some javascript)
Do you think is possible to do this?
If yes how to?
Does this still need some foreach loop?
Thank you for helping

E.g.:
core_table
id* unit quantity description
1 car 3 Description 1
2 bike 74 Description 2
adjunct_table
core_id* meta_key* meta_value
1 47 Description of key n.47 first row
2 47 Description of key n.47 second row
* = (component of) PRIMARY KEY

Related

Json Dataset Errors: Cannot read property 'parent' of undefined & Cannot set property '_node' of null

I'm venturing into very uncharted territory (for me) and I would appreciate some input. I've been through S/O but any references to these errors are for what appear to be different scenarios.
In essence, I have a pretty standard mySQL query that creates an associative array of approximately 70 child arrays with 7 items within each array. I then use 'json_encode' to make it ready for use in a grid. A print_r lists everything correctly with all data intact (see below).
Array
(
[0] => Array
(
[c_ksa] => 1
[urgency] => 3
[position_id] => 1000115
[position_root] => Maintenance C&M
[position_area] => Construction West
[positionmgr_uid] => dale.jones#gmail.com
[last_name] => Jones
)
[1] => Array
(
[c_ksa] => 1
[urgency] => 1
[position_id] => 1000172
[position_root] => Creative C&M
[position_area] => Design/Build
[positionmgr_uid] => anita.smith#gmail.com
[last_name] => Smith
)
However, in Dev Tools I'm getting the two errors:
Cannot read property 'parent' of undefined
and
Cannot set property '_node' of null
I have no idea where to start looking. Are these data type errors? Is this 'object' related? I don't have much experience in this area - but I'm willing to learn if someone can point me in the right direction. Thank you!
After much more exploring, I found the problem. In my application I have a table containing a column listing the managers in an org who sponsor an employee into a specific program. Because a manager can sponsor more than one employee, there will be repeats (duplicates) in this column. I had set the 'id' in my SQL query ("AS id") to that column so when I tried to use the resulting array while referencing the 'id' there were conflicts due to the duplicates. When this was fixed, all errors were resolved. Lesson learned ...

How to remove element from array or move to new array in php using javascript

I have an array $item in my Yii2 project, and I'm using dual listbox for elimination useless headers, I got headers from an imported Excel file.
The dual listbox has 2 box, left-box (Unselected) and right-box(Selected).
At the firsttime, all headers from $item showed in left-box, and then user drag/move the headers that want to use from left-box to right-box. When the headers moved to right-box, each headers has data-sortindex as an id.
So the the unselected headers in left-box doesn't has a data-sortindex as id.
Can anybody tell how to remove all the unselected headers from the array?
Array
Array
{
[0] => Array
{
[0] => nim
[1] => class
[2] => age
[3] => gender
[4] => address
[5] => skill
}
}
Dua listbox
From the picture above, you can see that I want to remove the class and gender from $item array when the button clicked.
I have another idea like set the selected headers to a new array. But I need the array's name still $item.
Any help would be appreciated. Thanks :)

jquery datatable column for images

I'm using php to generate the array and JSON encode it echoing it back to the javascript to render.
JS isn't my forte by a long shot and I've found a couple of examples but they don't make sense to me.
Sure the penny will drop with some direction and I'm sure its an easy one when I see it.
$(document).ready(function() {
var dataTable = $('#result-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"searchdata.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".result-grid-error").html("");
$("#result-grid").append('<tbody class="result-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#result-grid_processing").css("display","none");
}
}
} );
The array comes in from with the first column as a url to the image for the colour the remaining columns are versions of that colour.
So how do I make it so that the first column it renders the url as the image given from the array.
Array
(
[0] => Array
(
[0] => http://red.jpg
[1] => version 1
[2] => version 2
[3] => version 3
[4] => version 4
)
[1] => Array
(
[0] => http://silver.jpg
[1] => version 1
[2] => version 2
[3] => version 3
[4] => version 4
)
)
I read through loads of pages but they don't fully make sense to me.. sure I'm just being thick!!
datatables render column
Excuse me decided that rather than waiting for the a JS solution if I was to wrap the string in html before passing onto the JS then this should fix my issue and yes it does. So now I can format the img etc and move.
Apologies for lack of grey matter last night.

Highcharts how to use js object in PHP widget

My question is similar to this one: Highcharts how to use JavaScript variable as series data source? - except mine is a php variable.
I'm using https://github.com/2amigos/yii2-highcharts-widget this package with Yii2 and I've generated a data array which looks like this:
Array
(
[0] => {y: 37.50, color: "#BF0B23"}
[1] => 49.25
[2] => 52
)
I cast the numbers to floats when generating this array, but I couldn't do this with the object. When the graph is rendered the columns all work fine except for the one that I am trying to change the colour for.
The JS ends up like this "data":[37.5,49.25,"{y: 52.00, color: \"#BF0B23\"}"]. The js object being quoted basically means it isn't rendered. I've tried array_values(), (casting) and some other weird and wonderful manipulation to try and remove the quotes. I'm hoping there is a way to easily remove the quotes?
I guess you are trying to convert PHP hash into JSON, which then should be rendered by highcharts?
Try json_encode php function for that - http://php.net/manual/en/function.json-encode.php
Ok, I managed to figure out how to do it. Thanks #paweł-fus because your comment got me thinking about it a different way.
In my previous non-yii2, non 2amgios package I was generating my object as a string and writing it directly into JS.
if($d['ATTENDING'] === $data['ATTENDING'])
{
$a[] = array($data['ATTENDING'] => '{y: ' . number_format($data['PERCENTAGE'], 2) . ', color: "#BF0B23"}');
} else {
$a[] = array($data['ATTENDING'] => number_format($data['PERCENTAGE'], 2));
}
So my array either showed the column value, or if the column value was special it showed the value and i also changed its colour. This was represented as a JS object.
What I need to do was this though, create an inner array for the js object in php and typecast the value so it wasn't a string.:
$a[] = array($data['ATTENDING'] => ['y' => (float) number_format($data['PERCENTAGE'], 2), 'color' => '#BF0B23']);

Passing and handle 2D Array from Ajax to Php

I passing an array from Jquery(post) to php like:
[["a","b","c"],["aa:","bb","cc"]]
How to extract this array in php?
My code is:
UPDATE
$data = json_decode($_POST['data']);
print_r($data);
This code return :
Array
(
[0] => Array
(
[0] => as
[1] => as
[2] =>
)
[1] => Array
(
[0] => asas :
[1] => as
[2] => text
)
)
Instead of passing an array. You can tackle this two different ways
1) encode everything in JSON and pass it to php.
2) take everything that you need from the form and serialize it. Then explode the serialized data in your language of choice.
Passing arrays will not work the way you think it will. So it's best to just serialize the data and then do what you need. Using loops is a waste of time and CPU resources that could slow down the users experience.

Categories