I'm getting data from multiple API requests and storing each in a separate MySQL table. For each request I have an associated table, with field names matching the JSON API response. Since I'm not using all of fields from the API, I'm finding the fields in the MySQL table and using that to create the prepared statement with PDO, then feeding the results array into that for execution. Here's the function that accepts the statement and the results array:
function insert_array($sql,$args)
{
$this->connect();
$q = $this->con->prepare($sql);
foreach($args as $record) {
$q ->execute($record);
echo "<pre>";var_dump($record);echo "</pre>";
$arr = $q->errorInfo();
print_r($arr);
}
$this->disconnect();
return $q;
}
The last three lines in the foreach loop are just for debugging.
This worked fine for my first request, but no records are inserted, and I receive HY093, for others.
For the one that works, the prepared statement ($sql) comes out as
INSERT INTO fs_dynamicagents (agent_id, firstname, lastname) VALUES (:agent_id, :firstname, :lastname) ON DUPLICATE KEY UPDATE firstname=:firstname, lastname=:lastname
I'm finding unique fields first, so that's why agent_id isn't in the update statement. This inserts successfully, even though I'm not using all the fields. Here's the output of the var_dump and errorInfo:
array(4) {
["agent_id"]=>
string(3) "002"
["firstname"]=>
string(9) "Bill"
["lastname"]=>
string(5) "Murray"
["password"]=>
string(4) "1212"
}
Array ( [0] => 00000 [1] => [2] => )
Now here's an example of one that doesn't work:
INSERT INTO fs_queue (name, record) VALUES (:name, :record) ON DUPLICATE KEY UPDATE record=:record
And part of the first API record:
array(79) {
["name"]=>
string(7) "Choice1"
["fc_name"]=>
string(7) "Choice1"
["friendlyname"]=>
string(7) "Choice1"
["record"]=>
string(1) "1"
["agent_announcement_file"]=>
string(0) ""
["play_agent_announcement_file"]=>
string(1) "0"
["incoming_call_script"]=>
string(0) ""
["caller_agent_match"]=>
string(1) "0"
["survey_id"]=>
NULL
}
Array ( [0] => HY093 [1] => [2] => )
You can see I haven't included all 79 of the fields, but I've tried to include at least the fields with "name" in the label, and an empty string and a null value. Nothing but "name" and "record" should be bound, so I don't see those as a problem.
Every instance I've found online for this error code was due to a type (or case sensitivity). I've tried defining "record" as an int and a varchar.
Well, I had hoped that the process of typing this out would expose the problem to me, but no such luck. If a night's sleep doesn't help, I'd love to hear thoughts.
Edit: Something else I have tried is removing the ON DUPLICATE UPDATE section (and emptied the table so there will not be any duplicates) so that each parameter is only bound once. It sounds like that was a bug a few years ago that has been fixes, but even without that I receive the same error.
Edit2: Hmm, even stranger, removing the ON DUPLICATE UPDATE causes some of my previously working statements to fail with the same error. Not all of them, and of course those that don't fail for that reason will fail if it runs into a duplicate.
Edit3: Something else I have tried is removing the binding-by-key for the update statement, and changing this to
INSERT INTO fs_queue (name, record) VALUES (:name, :record) ON DUPLICATE KEY UPDATE record= VALUES(record)
I didn't think that would fix it, because it succeeds the first way on other tables, and this does in fact still fail.
Edit4: I was able to make one of these work by adding fields to the MySQL table so that all the columns from the input array were being used. However, I don't think that's what really solved the problem, because I have others succeeding without all columns being used, even in the middle of the array.
Ok, I figured it out. First, I was not setting ATTR_EMULATE_PREPARES at all, which means it would default to the database preparation engine unless the PDO engine was required. Since MySQL cannot re-use placeholders, it was using the PDO engine. Setting that to false would force the MySQL engine, and all requests would fail.
So the PDO engine can re-use placeholders, but however that happens it's not very good at finding the values. Even trying to find 2 out of 3 columns it would sometimes fail. So rather than let PDO sort it out, I'm throwing out everything I don't need before I send it to be inserted.
I'm using a function to delete columns that I found here.
<?php
function delete_col(&$array, $key) {
return array_walk($array, function (&$v) use ($key) {
unset($v[$key]);
});
}
$table_fields = array("id","fruit");
$insert_data = array(
array(
"id" => "1",
"fruit" => "Apple",
"color" => "Red"
),array(
"id" => "2",
"fruit" => "Apple",
"color" => "Green"
),array(
"id" => "3",
"fruit" => "Pear",
"color" => "Green"
)
);
foreach($insert_data[0] as $key=>$value) {
if(!in_array($key, $table_fields)) {
delete_col($insert_data, $key);
}
}
echo "<pre>";
print_r($insert_data);
echo "</pre>";
?>
This assumes that the first record will have an entry for every column. I do have some where that's not true, but so far it hasn't caused problems, but I will probably end up rewriting this to go through each row.
Related
I have a returned string result from an API and it looks like this.. for the life of me, I cannot retried the WorkID value!
The returned string is a json string:
{"notes":"","RecordsStatus":"{\"0\":{\"WorkID\":\"0090210\",\"Message\":\"Record Created\"}}"}
It has two parts:
“notes” and “RecordStatus”.
If message is empty, means the batch is imported without error.
In RecordStatus, there are two parts too.
First is the index number of the record, and it has second part that the key for the record created(in my case it’s the WorkID) and a message tells the record is created or updated(in my case, it’s created).
Array
(
[notes] =>
[RecordsStatus] => {"0":{"WorkID":"0090210","Message":"Record Created"}}
)
Do a Var_dump() of decoded_json results in this:
array(2) {
["notes"]=>
string(0) ""
["RecordsStatus"]=>
string(52) "{"0":{"WorkID":"0090210","Message":"Record Created"}}"
}
I tried
foreach($decoded_json as $item) {
$uses = $item['RecordsStatus'][0]['WorkID']; //etc
}
but does not work
I have an array which I return from a class. It contains data for me which I need in the controller of my application. However something strange is happening. Some values are when I get them by key not defined. But when I print the whole array they are defined. But that's not all. Some keys return their value, some don't.
To test if the key can be found I used array_key_exists(), which returned true. Let's get to the example. When I print $this->case->data, it will return the following;
[id] => 1
[ticket_number] => 2334
[user_id] => 2
[ticket_state] => 1
Which is okay. To test this out I tried returning the ticket_number value. ($this->case->data['ticket_number']). It worked perfectly and returned it's value. However when I try to return ticket_state ($this->case->data['ticket_state']) I get an undefined as value.
It might be that I'm missing something here. What am I doing wrong? And if I'm doing it wrong how can it be that ticket_number works, but ticket_state does not?
Edit:
I do get undefined as value returned. Not an undefined index error. I did a var_dump() on the variable.
array(4) { ["id"]=> string(1) "1" ["ticket_number"]=> string(14) "2334" ["user_id"]=> string(1) "2" ["ticket_state"]=> string(1) "1" }
Edit II:
My code where I try to receive the value is the following simple if statement;
if($this->case->data['ticket_state'] == 2){
$this->case->reopen();
}
I've tried adding the 2 in quotes, but since $this->case->data['ticket_state'] is undefined it the statement will be executed regardless. (Which I found strange too. Why should it still be executed when undefined is not the same as 2 or '2'?).
The current value of my column ticket_state is 1.
I'm receiving data in the following format from a multi-checkbox
["Ethnicity"]=>
array(3) {
["Maori"]=>
string(5) "Maori"
["Pacific Peoples"]=>
string(15) "Pacific Peoples"
["Other European"]=>
string(14) "Other European"
}
I'm trying to get this into a multi-checkbox in Jira via an API call using the following segment
'customfield_11337' => [
"value" => $data["Ethnicity"]
],
But this returns an error string(21) "data was not an array"
So I've tried to massage the data into a single array using
$ethnicityArray = array();
foreach ($data["Ethnicity"] as $eth => $value) {
array_push($ethnicityArray, $value);
}
But this returns the same error. I should note that I've got no problem populating radio buttons, text fields etc in Jira via the same method. It just seems to be checkboxes I can't get right.
How do I go about solving this using PHP?
The correct solution was to get the data into a format that looks like:
'customfield_11333' => [["value" => "Asian"], ["value" => "Other"]]
Hard-coded query
$stock = DB::select("SELECT * FROM reports_finra WHERE symbol = ? ", array('CWCO')); // works and returns valid result set
Array (
[0] => Array ( [query] => SELECT * FROM symbols [bindings] => Array ( ) [time] => 37.4 )
[1] => Array ( [query] => SELECT * FROM reports_finra WHERE symbol = ? [bindings] => Array ( [0] => CWCO ) [time] => 27.07 )
)
# result set when var_dump($stock) ( [1]'s query )
array(11) {
[0]=> object(stdClass)#5939 (7) { ["date"]=> int(20140116) ["symbol"]=> string(4) "CWCO" ["id"]=> int(1498) }
[1]=> object(stdClass)#5940 (7) { ["date"]=> int(20140117) ["symbol"]=> string(4) "CWCO" ["id"]=> int(8515) }
[2]=> object(stdClass)#5941 (7) { ["date"]=> int(20140121) ["symbol"]=> string(4) "CWCO" ["id"]=> int(15526) }
...
}
Dynamically binded variable being passed to query
$symbol = $symbol->symbol;
echo $symbol;
echo '<br />';
$stock = DB::select("SELECT * FROM reports_finra WHERE symbol = ? ", array($symbol));
$query = DB::getQueryLog();
print_r($query);
echo '<br />';
var_dump($stock); exit;
Results
CWCO // the result from echoing $symbol
Array ( // getQueryLog()
[0] => Array ( [query] => SELECT * FROM symbols [bindings] => Array ( ) [time] => 36.06 )
[1] => Array ( [query] => SELECT * FROM reports_finra WHERE symbol = ? [bindings] => Array ( [0] => CWCO ) [time] => 27.55 ) )
array(0) { } // var_dump($stock);
As you can see, when I pass the value of symbol into the query as a hard-coded value, I get the desired result set. However, when I pass the value in dynamically, the query returns an empty result set.
I have been going back and forth with this for quite a while now and am out of ideas on how to further troubleshoot this. Even more perplexing is the fact that these exact queries work in my dev environment but not when I pushed to prod.
Through troubleshooting, prior to realizing that when I pass in the raw, hard-coded value, that I was getting a valid result set, I ensured that there were only minor PHP / MySQL version differences between dev and prod ENVs. I triple checked that the user had the proper DB permissions. And, I tailed out my log files. None of these actually help shed any light onto what is actually going wrong here though.
As I just recently started to get back into development and have only been playing with L4 for a week or two, I'm hoping someone with more experience will see what it is that is causing this (I have an odd feeling that it is going to be an ID10T error..).
I look forward to any advice and insight you may have to offer.
-- Edit --
As the query is returning an (empty) result back (and not throwing an error), the query appears to be "working" as far as MySQL is concerned. However, it is not returning the result set for whatever reason. I am not sure if this has to do with PDO, Eloquent, or something else entirely. It's a basic SELECT * query on a non-related table; it shouldn't be this much hassle.
And, I'm quite perplexed why the other select statements work without an issue, but this one is not. Granted, I am querying a table that is not related to the model (there is no DB/L4 relationships defined; this is a once-off Select statement in order to do some essential math).
Unfortunately, I can't proceed until I get this worked out...
I stated in the question that I thought this might be an ID10T error, and it was.
After doing a var_dump($symbols) on it again, and paying a little closer attention, I realized that there was a trailing space behind each of the $symbols which didn't match anything in the table. Aha! So, the query was executing successfully and returning the correct results all along; go figure. ;)
Interesting thing to note, I should have done a trim on the $symbols before inserting them into the DB table using Laravel's http://laravel.com/docs/eloquent#accessors-and-mutators as pointed out by the awesome AndreasLutro in #laravel.
I have a html form with checkboxes. Someone selects one or more checkboxes and hit the delete button then it will delete the files references out of the database and delete the files out of Amazon S3. This is the code I used to find all the checkboxes
$checkbox_select = JRequest::getVar('checkboxselect', '', 'POST'); //just a Joomla way of doing a $_POST with extra security
var_dump($checkbox_select); //this returns: array(2) { ["video_1.mp4"]=> string(2) "on" ["video_2.mp4"]=> string(2) "on" ["video_3.mp4"]=> string(2) "on"}
// Localize and sanitize each individual value
foreach (array_keys($checkbox_select) as $element) {
$deleteNames[] = $db->quote($element);
}
var_dump($deleteNames); //array(3) { [0]=> string(13) "'video_3.mp4'" [1]=> string(13) "'video_2.mp4'" [2]=> string(13) "'video_1.mp4'" }
My problem is with Amazon S3 and multiple file deletion. The format I need to put S3 deletion in is quite confusing:
$s3->delete_objects('mybucket', array(
'objects' => array( // accepts a *list* of one or more *hashes*
// a *hash* that contains a "key" key with a value, and maybe a "version_id" key with a value
array('key' => 'object (file) name'),
// a second hash representing a file
// a third hash representing a file
// and so on...
),
));
As far as I understand (from S3 delete_objects function) the final associated array has key as the actual key value. With the last var_dump I've got all video names in an array now I just need to convert that array to a bunch of arrays in this format:
array ('key' => 'video_1.mp4'),
array ('key' => 'video_2.mp4'),
array ('key' => 'video_3.mp4'),
...and so on
How can I create these arrays? Should I be using the first var_dump I have or the second (they both have the video file names listed)? Thanks in advance.
You can use foreach to loop over your array and create a new array in the desired format.
Example:
<?php
foreach (array_keys($checkbox_select) as $element) {
$deleteNames[] = array('key' => $db->quote($element));
}
Untested, may contain errors
have a look at this post in the php documentation for array_push(). You'll get a brief idea of how to achieve it.