Adding a new field to data extracted from a database call - php

As part of a search routine for a specific crop, I'm making two calls to the same database table, merging the results and sending them down the line. The first call looks for data relating to the searched-for crop (e.g. "beans"). The second call looks for data relating to the crop group of that crop (e.g. legumes).
Data returned from the first call will be more relevant/focused than that from the second call. I want to add an identifier to the respective data sets that reflects this so that I can subsequently sort/present the data on the basis of relevance in my Vue component.
The following code extracts the crop-specific information from the database; how can I add/insert/append a new variable (e.g. "relevance" = 1) to each row in $factsheets before I "array_merge" it with the data returned from the crop-group sql call?
(For sake of simplicitly, I've not included the code that determines the crops.id value from the name of the crop entered by the user.)
public function getFactsheets($cropId){
$factsheets = Factsheet::whereIn('crop_id',$cropId)
->join("crop_factsheet as cf","factsheets.id","=","cf.factsheet_id")
->join("crops as crops","crops.id","=","cf.crop_id")
->select('crops.name','title', 'factsheets.id', 'shortdesc', 'shortimg', 'factsheets.slug')
->orderBy('crops.name')
->get()->toArray();
return $factsheets;
}
Thanks, Tom.

If you give & to value so whatever changes will happen to value will directly saved on its address.
foreach($factsheets as $key => &$factsheet){
$factsheet['relevance'] = 1;
}
Working demo.
Here is concise explanation of references in official doc.

you can simply do a foreach
foreach($factsheets as $key => $factsheet){
$factsheet['relevance'] = 1;
}

Related

Accessing releated field

In FileMaker I have (a.o.) two related tables, where Betreuer_id of table "studentpaper" refers to id of table "Betreuer".
With help of FileMaker's PHP API, I want to access a record in "studentpaper" including the releated fields. Howerver, the later poses a problem. Consider the following PHP code:
$findCommand =& $fm->newFindAllCommand('studentpaper');
$result = $findCommand->execute();
$records = $result->getRecords();
$record = $records[0];
echo $record->getField('Titel'); // okay
echo $record->getField('Betreuer_id'); // okay
echo $record->getField('Betreuer::Name');
// ERROR: get empty string, even related record has a non-empty field
I have expected for "Betreuer::Name" the correct related result, as usually in FileMaker (and as I get in studentpaper's layout). However, I get only an empty string.
What am I doing wrong? Does the relation in FileMaker's PHP-API differs from the "usual" FileMaker approach?
In case anybody is interested, I found the solution on my own.
The problem was that the field wasn't defined (in the layout) as normal text input, but as selection field resticted by a value list.
Thus, one needs to access the value not via the usual getField function but by one of the functions related to value lists. In my case, getValueListTwoFields did the job.

Showing progress bar while fetching data [duplicate]

I have this while loop, that basically loops through a lot of records in a database, and inserts the data in another:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
}
(The script has been shortened for easy reading - the correct one has a much longer array)
I would like to do this more graphical, and show a progress bar on how far it has went, instead of just seeing a page loading for a few minutes (there are ~20.000 rows in this one - I have tables with much more data)
I get that you could get the total number from the old database, and I could also easily put the current number into a variable like this:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
$i = 0;
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
$i++;
}
But now I need to actually fetch $i and display it - or something like it.
How is this "easily" done?
The code for the progress bar can either be in the same document as the while loop, or in another if easier.
You can do a "master" file that does an ajax to this first file to run a single query. You could get all the entry id's in this master file, and then pass it as a parameter to the second file that does a single query. Store these ids in a javascript array.
Create a function that does this, and when the first ajax is done, move to the second element of the id array, and do another ajax with a second parameter. That's how magento imports are done by the way :)
If you need further explanations, let me know, I tried my best to explain, but may have not been perfectly clear.
// you generate this javascript array using php.
// let's say you have all the ids that have to be processed in $Ids php array.
Ids = [<?php echo implode(',', $Ids); ?>];
function doAjax(i) {
$.ajax({ // using jquery for simplicity
'url': "ajax.php?id=" + Ids[i],
}).done(function(){
if ( i >= 0 ) {
// at the point you know you're at ((Ids.length-i)/(Ids.length) * 100) percent of the script
// so you can do something like this:
// $('.progressbar').css('width', ((Ids.length-i)/(Ids.length) * 100) + '%');
doAjax(i-1);
}
});
}
doAjax(Ids.length); // starting from the last entry
So, just to explain what this does. It starts by declaring a global javascript array that has all the ids that will need to be changed.
Then I declare a recursive ajax function, this way we can make sure that only one ajax runs at any single time (so the server doesn't blow up), and we can have a fairly accurate progress. This ajax function does the following:
Sends a request to ajax.php?id=xxx - where xxx is one of the ids in the javascript array.
In the file, we get the id ($_GET['id']), you take it from the old database, and insert it in the new one. This is only for one entry.
when the ajax is done, it goes to the done() function. Since we start the doAjax() function with the last element, we do the next iteration doAjax(i-1). Since we're going backwards in the array, we check if the key is positive. If it's not, the script will stop.
That's about it.
You can't. The php is first interpreted by the server and then send to the user as HTML-Code.
The only possibility would be creating a html-page and call the php-script with AJAX.

Wrong dataype for in_array

Good morning.
I'm currently trying to build a very basic caching system for one of my scripts. The cache is JSON data and contains only 1 key and it's value, but many individual fields, something like this;
{"Item1":"Item1 Description"}
{"Item2":"Item2 Description"}
{"Item3":"Item3 Description"}
What I'm intending to do is;
First check if a cache file is available
Then check if an item exists in the cache
Then add the new item along with it's description if it's not already in the cache...
...or return the item description if it's not there.
All data being stored is strings. The cache file doesn't store any other type of data.
I've put together a basic function but I'm having trouble getting it functioning;
function ItemIsInCache($CacheFile, $ItemId) {
if(file_exists($CacheFile)) {
$json = json_decode(file_get_contents($CacheFile, true));
if(in_array($ItemId, $json)) { // <<
$itemname = array_search($ItemId, $json);
return itemname;
} else {
$item[$itemId] = GrabItemName($ItemId);
$itemname = array_search($ItemId, $json); // <<
return $itemname;
}
} else {
$item[$ItemId] = GrabItemName($ItemId);
$ejson = json_encode($item);
file_put_contents($CacheFile, $ejson);
return $item[$ItemId];
}
}
Notes
GrabItemName is a different function that returns the description data based on the $ItemId.
The warnings I'm getting are Wrong datatype for second argument in both array_search() and in_array(), on lines 4 and lines 9 respectively (those are the line numbers in the above code - due to the nature of my script these numbers are later on) -- for simplicity, I've marked the problem lines with // <<.
The function is running in a loop which I've no problems with. The problems lie within this function.
What currently happens
Right now, if the cache doesn't exist, it creates it and adds the first item from the loop to the cache file in it's respective JSON format (that fires since the cache file doesn't exist, so after the final else statement).
However, items from the loop after that don't get added, presumably because the file exists and there's something wrong with the code.
The last part of the function works exactly as I want it to but the first part does not.
Expected behaviour with fixed code
Check cache > Return description if item exists ELSE add new item to cache.
The items and their associated descriptions will NOT change, but I'm pulling them from a rate limited API, and I need to ensure I cache whatever I can for everyones benefit.
So, any ideas what I'm doing wrong with the function? I'm sure it's something incredibly simple that I'm overlooking.
Your file is not JSON for an erray. The correct JSON for an array is
[
{"Item1":"Item1 Description"},
{"Item2":"Item2 Description"},
{"Item3":"Item3 Description"}
]
You're missing the brackets around the array, so you just get a single object.
When creating the initial file, you need to do:
$ejson = json_encode(array($item));
so that it's initialized as an array of one item, not just an item.

PHPFlickr script...could this be cleaner/leaner?

OK, here's my dilemma:
I've read all over about how many guys want to be able to display a set of images from Flickr using PHPFlickr, but lament on how the API for PhotoSets does not put individual photo descriptions. Some have tried to set up their PHP so it will pull the description on each photo as the script assembles the gallery on the page. However, the method has shown how slow and inefficient it can be.
I caught an idea elsewhere of creating a string of comma separated values with the photo ID and the description. I'd store it on the MySQL database and then call upon it when I have my script assemble the gallery on the page. I'd use explode to create an array of the photo ID and its description, then call on that to fill in the gaps...thus less API calls and a faster page.
So in the back-end admin, I have a form where I set up the information for the gallery, and I hand a Set ID. The script would then go through and make this string of separated values ("|~|" as a separation). Here's what I came up with:
include("phpFlickr.php");
$f = new phpFlickr("< api >");
$descArray = "";
// This will create an Array of Photo ID from the Set ID.
// $setFeed is the set ID brought in from the form.
$photos = $f->photosets_getPhotos($setFeed);
foreach ($photos['photoset']['photo'] as $photo) {
$returnDesc = array();
$photoID = $photo['id'];
$rsp = $f->photos_getInfo($photoID);
foreach ($rsp as $pic) {
$returnDesc[] = htmlspecialchars($pic['description'], ENT_QUOTES);
}
$descArray .= $photoID."|~|".$returnDesc[0]."|~|";
}
The string $descArray would then be placed in the MySQL string that puts it into the database with other information brought in from the form.
My first question is was I correct in using a second foreach loop to get those descriptions? I tried following other examples all over the net that didn't use that, but they never worked. When I brought on the second foreach, then it worked. Should I have done something else?
I noticed the data returned would be two entries. One being the description, and the other just an "o"...hence the array $returnDesc so I could just get the one string I wanted and not the other.
Second question is if I made this too complicated or not. I like to try to learn to write cleaner/leaner code, and was looking for opinions.
Suggestions on improvement are welcome. Thank you in advance.
I'm not 100% sure as I've just browsed the source for phpFlickr, and looked the the Flickr API for the getInfo() call. But let me have a go anyway :)
First off, it looks like you shouldn't need that loop, like you mention. What does the output of print_r($rsp); look like? It could be that $rsp is an array with 1 element, in which case you could ditch the inner loop and replace it with something like $pic = $rsp[0]; $desc = $pic['description'];
Also, I'd create a new "description" column in your database table (that has the photo id as the primary key), and store the description in their on its own. Parsing db fields like that is a bit of a nightmare. Lastly, you might want to force htmlspecialchars to work in UTF8 mode, cause I don't think it does by default. From memory, the third parameter is the content encoding.
edit: doesn't phpFlickr have its own caching system? Why not use that and make the cache size massive? Seems like you might be re-inventing the wheel here... maybe all you need to do is increase the cache size, and make a getDescription function:
function getDescription ($id)
{
$rsp = $phpFlickr->photos_getInfo ($id);
$pic = $rsp[0];
return $pic['description'];
}

add a name value pair to posted data for joomla to consume and insert into DB

I'm trying to use the Joomla framework to make a create in the main content table.[http://docs.joomla.org/How_to_use_the_JTable_class] This works fine except that some data comes from posted variables and some from logic that happens when a file is uploaded moments before (store the random image name of a jpg)
$data=&JRequest::get('post');
this takes a ref to the posted values and I want to add to this Array or Object my field. The code I have makes the new record but the column images, doesnt get my string inserted.
I am trying to do something like$data=&JRequest::get('post');
$newdata=(array)$data;
array_push($newdata,"images"=>"Dog");
i make newdata as data is a ref to the posted variables and i suspect wont there fore allow me to add values to $data.
I'm a flash guy normally not a php and my knowledge is letting me down here.
Thanks for any help
Right, first thing:
$data=&JRequest::get('post');
$data is an array, you do not have to cast it. To add another element to the array as described in the comments do this:
$data['images'] = 'cats';
If you are using normal SQL to do the insert then you would do something like this to get the last inserted id e.g. the id of the row you just inserted:
$db = $this->getDBO();
$query = 'Some sql';
$db->setQuery($query);
if (!$db->query()) {
JError::raiseWarning(100, 'Insert failed - '.$db->getErrorMsg());
}
$id = $db->insertid();
If you are developing in Joomla I suggest you use the db functions provided to you rather than mysql_insert_id();
[EDIT]
If you want to use store then you can get the last inserted id like so:
$row->bind($data);
$row->check();
$row->store();
$lastId = $row->id;

Categories