How to generate a grid(Table) with a foreach - foreach

My problem is simple, but I'm beginning with cakephp. I'll explain my problem:
I have 2 tables:
Table: Expenditures
Columns:
sub_category_id
account_id
date
ammount
created
modified
description
Table: BudgetRecords
Columns:
budget_id
ammount
sub_category_id
created
modified
I have a 'home-work' to do, and my teacher wants me to do a report. This report will generate a table, and will show an balance (Expenditures.ammount - BudgetRecords.ammount), and each month (BudgetRecords.created, or Expenditures.date, whatever).
Here's my question: I'm trying to do a foreach, passing for each year (if exists), if a year exists, then execute a query for each month. But, how I do that with CakePHP? I've tried to do this only inside the Controller, and it runs fine. But returns me only the last month of the last year. Then, I've tried a different approach.
Inside the View, execute the query and search if exists the year. If exists, then search for this month. Then gives me back the result.
That's what I did:
Inside the View:
<table align="center" border="2" rules="All">
<tr>
<td>Valor:</td>
<td>Data:</td>
</tr>
<?php
for ($month = 1; $month <= 12; $month++) {
if (strlen($month) == 1)
$month = '0' . $month;
foreach ($Expenditure->SaldoMes($month) as $result) {
echo "<tr>";
echo "<td> R$:" . $result[0] . "</td>";
echo "<td> " . $result[1] . "</td>";
echo "</tr>";
}
}
?>
</table>
Inside the Controller:
public function SaldoMes($month = null) {
$month = 0;
for ($month = 1; $month <= 12; $month++) {
if (strlen($month) == 1)
$month = '0' . $month;
$query = "SELECT (SUM(ex.ammount) - SUM(br.ammount)) as total , br.created as data
FROM budget_Records br, expenditure ex
where SUBSTRING(br.created, 6, 2) = '" . $month .
"' and SUBSTRING(br.created, 6, 2) = SUBSTRING(ex.created, 6, 2)";
$this->set('Expenditure', $this->Expenditure->query($query));
foreach ($this->Expenditure->query($query) as $records) {
$this->set(('Total'), $records[0]['total']);
$this->set(('Data'), $records['br']['data']);
}
}
}
I hope I've explained my problem well enough for someone to show me a solution.

I think this will help
http://book.cakephp.org/2.0/en/controllers.html
This part is what you are looking for I think. Taken from that website.
<?php
# /app/Controller/RecipesController.php
class RecipesController extends AppController {
public function view($id) {
//action logic goes here..
}
public function share($customer_id, $recipe_id) {
//action logic goes here..
}
public function search($query) {
//action logic goes here..
}
}
"The view files for these actions would be app/View/Recipes/view.ctp, app/View/Recipes/share.ctp, and app/View/Recipes/search.ctp. The conventional view file name is the lower cased and underscored version of the action name."
So if you wanna just use another method like SaldoMes() then just call it in the view method.

#earlonrails, solved:
public function SaldoMes() {
$result = array();
for ($month = 1; $month <= 12; $month++) {
if (strlen($month) == 1)
$month = '0' . $month;
$query = "SELECT (SUM(ex.ammount) - SUM(br.ammount)) as total , br.created as data
FROM budget_Records br, expenditure ex
where SUBSTRING(br.created, 6, 2) = '" . $month .
"' and SUBSTRING(br.created, 6, 2) = SUBSTRING(ex.created, 6, 2)";
$this->set('Expenditure', $this->Expenditure->query($query));
foreach ($this->Expenditure->query($query) as $records) {
$result[$month][0] = $records[0]['total'];
$result[$month][1] = $records['br']['data'];
}
}
return $this->set('result', $result);
}
Using the $result array, now i can get my values.
Thanks for teh help.

Related

splitting a string into similar elements along with the values

I have a string like
$query = "date=20.10.2007&amount=400+date=11.02.2008&amount=1400+date=12.03.2008&amount=1500";
there are two variables named date and amount containing a value e.g date= 20.10.2007 and amount=400 and these two variables repeat itself with different values and each set (date & amount) are separated by '+' sign. Now i want to display this string like this:
Date Amount
20.10.2007 400
11.02.2008 1400
12.02.2008 1500
Need help
We can make judicious use of explode and preg_split here to get the output you want:
$query = "date=20.10.2007&amount=400+date=11.02.2008&amount=1400+date=12.03.2008&amount=1500";
$array = explode("+", $query);
$counter = 0;
echo "Date Amount\n";
foreach($array as $item) {
if ($counter > 0) echo "\n";
$parts = explode("&", $item);
echo preg_split("/=/", $parts[0])[1] . " ";
echo preg_split("/=/", $parts[1])[1];
$counter = $counter + 1;
}
This prints:
Date Amount
20.10.2007 400
11.02.2008 1400
12.03.2008 1500
The logic here is that we first split the query string on + to obtain components looking like:
date=20.10.2007&amount=400
Then, inside the loop over all such components, we split again by & to obtain the date and amount terms. Finally, each of these are split again on = to get the actual values.
Thanks a lot Tim Biegeleisen for your kind guidance. From your help i did it with this code below:
$str = "date=20.10.2007&amount=400+date=11.02.2008&amount=1400+date=12.03.2008&amount=1500"; $array = explode("+",$str);
$i = 0;
echo nl2br("Date Amount \n");
foreach($array as $item[$i])
{
parse_str($item[$i]);
echo $date;
echo $amount."<br>";
$i++;
}

Remove older $_GET from url

I've got some problems with my url on my website. I'm trying to get a link with the given GET parameters, but i'm getting my previous parameter aswell.
My url looks like this:
www.cdwinkel.dev/search-results?genre=Pop&medium=DVD&medium=Single .
It should be:
www.cdwinkel.dev/search-results?genre=Pop&medium=Single .
I'm running the following code:
$data['url'] = createurl();
function createurl(){
$i = 1;
$string = "?";
$keys = array_keys($_GET);
foreach($_GET as $get){
if($get != ""){
$string .= $keys[$i] . "=" . $get ."&";
$i++;
}
}
$string = rtrim($string, "&");
return $string;
}
$i = 1, because my first value in my array is empty.
And my button looks like this:
<a href='".$data['url'].'&medium='.$names[$i]."'>
I guess I should'nt set &medium=.$names[$i] in the href tag,
but I wont get the new $names[$i] in my function, so I won't get a new url if i wont add it in.
I'm looking forward to your responce.
Sincerely,
Kars Takens
At this point i've created an array with the right arraykeys and values.
$url = array_slice($_GET, 1);
This returns the following array:
array (size=2)
'genre' => string 'Pop' (length=3)
'medium' => string 'DVD' (length=3)
After this I decoded this into a new string:
genre=Pop&medium=DVD
I got 6 button which I created in a foreach loop, but i'm getting &medium='VALUE' Twice. This only happens after the first time. So the first time my button works well.
<?php
$names = array_keys($data['tellen']);
$i = 0;
foreach($data['tellen'] as $m){
echo "<li><a href='search-results?".$data['url'].'&medium='.$names[$i]."'>". $names[$i] ." <span class='product-amount'>(". $m[0]->count. ")</span></a></li>";
$i++;
}
Hopefully you can help me further with this information.
I solved my problem by adding this in my forloop:
foreach($data['tellen'] as $m){
if(isset($_GET['medium'])){
unset($_GET['medium']);
$url = array_slice($_GET, 1);
$data['url'] = urldecode(http_build_query($url));
}
echo "<li><a href='search-results?".$data['url'].'&medium='.$names[$i]."'>". $names[$i] ." <span class='product-amount'>(". $m[0]->count. ")</span></a></li>";
$i++;
}

Make message_tags linkable using offset attribute in facebook api

I'm getting this post object from Facebook api :
{
"id"=>"XXX",
...,
"message"=>"abcd efg hijkl mn The New York Times opqr",
"message_tags"=>{
"18"=>[{
"id"=>"5281959998",
"name"=>"The New York Times",
"type"=>"page",
"offset"=>18,
"length"=>18
}]
},
...
}
How can I make a link in rails to facebook page like using offset & length attributes ? Result would be like this :
abcd efg hijkl mn The New York Times opqr
I had to do this just now, but in PHP. This was my solution:
/**
* Get message HTML
*
* #param string $text The message text
* #param array $tags The tags array
* #return string HTML message string with linked tags
*/
public static function getMessageHtml($text, $tags) {
$doc = new DOMDocument;
$doc->appendChild($doc->createTextNode($text));
if (is_array($tags)) {
foreach ($tags as $tag) {
$tag = $tag[0];
$start = 0;
foreach ($doc->childNodes as $child) {
if ($tag['offset'] < $start + strlen($child->nodeValue)) {
$meat = $child->splitText($tag['offset'] - $start);
$tail = $meat->splitText($tag['length']);
$a = $doc->createElement('a');
$a->setAttribute('href', '//facebook.com/' . $tag['id']);
$a->setAttribute('title', $tag['name']);
$meat->parentNode->replaceChild($a, $meat);
$a->appendChild($meat);
break;
}
$start += strlen($child->nodeValue);
}
}
}
return trim($doc->saveHTML());
}
This has worked in all my test cases so far, but it may be dodgy if tags overlap or are nested. I'm not sure if Facebook ever returns tags like that.
Hopefully you can easily port this to Ruby.

Jquery Mobile data-autodividers

Is there a way to have the auto-dividers sort by last name?
I don't think it should have anything to do with the php code, but I thought I would include it for a reference below:
$result = mysql_query("SELECT * FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_lastname`");
while($row = mysql_fetch_array($result)) {
echo '<li>' . $row['patient_firstname'] . ' ' . $row['patient_lastname'] . '<span class="ui-li-count">DOB: ' . $row['patient_dob'] . '</span></li>';
}
Appreciate any help!
You can do the sorting in the front-end by selecting the list items and sorting them afterward. In the example below, instead of selecting the text content of the list items, you can select the last-name value.
var listContentArray = listViewInstance.find('li').not('.ui-li-divider').get();
listContentArray.sort(function (a, b) {
var first = $(a).text(),
second = $(b).text();
if (first < second) {
return -1;
}
if (first > second) {
return 1;
}
return 0;
});
Then you can destroy the content of the listViewInstance, re-append the elements in the listContentArray, and finally refresh the listView component.
You can download a fully functional example that does all of this at:
http://appcropolis.com/page-templates/autodividers/
Couldn't find a way to display Firstname then Lastname and autodivide by Lastname, so I just replaced the code with:
' . $row['patient_lastname'] . ', ' . $row['patient_firstname'] . '
which displays: "Lastname, Firstname" and autodivides by Lastname. It'll have to work for now.

jquery autocomplete remote source tried EVERYTHING !! but no good

i have been trying to implement jquery ui autocomplete feature.. and the basic html code is xactly the same as given on-
http://jqueryui.com/demos/autocomplete/#remote
I have tried all combinations/ code snippets for "search.php" such as-
1)
<?php
if ( !isset($_REQUEST['term']) )
exit;
// connect to the database server and select the appropriate database for use
$dblink = mysql_connect('localhost', 'root', '') or die( mysql_error() );
mysql_select_db('research');
$rs = mysql_query('select uname,email,password from login where uname like "'. mysql_real_escape_string($_REQUEST['term']) .'%" order by uname asc limit 0,10', $dblink);
// loop through each zipcode returned and format the response for jQuery
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['uname'] .', '. $row['password'] .' '.$row['uname'] ,
'value' => $row['uname']
);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
2)
<?php
include("includes/connect.php");
$query = "SELECT uname from login WHERE uname LIKE '%" . addslashes($_GET['term']) . "%'";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
foreach($row as $val)
$tab[] = $val;
}
print json_encode($tab);
?>
3)
<?php
include("includes/connect.php");
$term = $_REQUEST['m']; // where name of the text field is 'm'
$query = "SELECT * FROM login WHERE uname LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while($obj = $result->fetch_assoc()) {
$arr[] = $obj['nome'];
}
echo json_encode($arr);
?>
But still nothing is working !! that is when i type into the text box for autocomplete there are no results shown. what could be the error ? are there any alternative solutions ?? Please help !!!
The variable that you pass into json_encode must be an array of strings.
e.g. ["red","green","blue"]
or an array of object literals e.g. [{"value" : "red"},{"value" : "green"},{"value" : "blue"}]
Each time through the loop you need to append the item to the existing items.
I notice, in all 3 code snippets, that you assign the current item to your array variable, instead of appending it. When the loop completes, the only item in your array will be the item processed most recently by the loop.
So unless what you type in the field matches that one item, the autocomplete isn't going to show anything.
Here is my PHP code to build an array of strings before sending it back to the file that made the request.
$fetchedArtists = $db->query($queryToGetArtists );
$json = '[';
$first = true;
while($row = $fetchedArtists->fetch_assoc())
{
if (!$first)
{
$json .= ',';
}
else
{
$first = false;
}
$artist = $row['artistName'];
$json .= '{"value":"'.$artist.'"}';
}
$json .= ']';
echo $json;

Resources