AngularJS filtering json data - angularjs

I have a column in mysql database called "month" and the values are 1 for January, 2 for February and so on.
In my AngularJS app, I use a get request to pull the json array from my php file. Is there a way to filter "data" so I can request only posts that contain the column month which would allow me to do an if statement, for instance if (month == 1){ filter only data which contain month value of 1}
Here is my code so far:
app.controller('TimeController', function($scope, $filter, $http) {
$http.post('ajax/getQuotes.php').success(function(data){
$scope.monthNumber = $filter('date')(new Date(), 'M');
if ($scope.monthNumber == 1){
}
$scope.quote = data;
angular.element(document.getElementById('log')).html( $scope.monthNumber);
});
This is my PHP code:
<?php
include('../includes/config.php');
try {
//Connect to the database, store the connection as a PDO object into $db.
$db = new PDO("mysql:dbname=".$DB_NAME.";host=".$DB_HOST.";charset=utf8", $DB_USER, $DB_PASS );
//PDO will throw PDOExceptions on errors, this means you don't need to explicitely check for errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//PDO will not emulate prepared statements. This solves some edge cases, and relives work from the PDO object.
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Prepare the statement.
$statement = $db->prepare("SELECT * FROM quotes");
//Execute the query
$statement->execute();
//Fetch all of the results.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
//$result now contains the entire resultset from the query.
//create a temp array
$arr = array();
//loop through mysql tables
if ($statement->execute()) {
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row;
}
}
array_unshift($arr, null);
echo json_encode($arr);
/*** close the database connection ***/
$db = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Is it possible to do a for each loop and push json data?
$.each { if $scope.quote.month == 1){ items.push ; } }

Related

How can i get top 15 occurrences in an array and use each value to fetch data from mysql database?

I am currently working on a project (A music website) with PHP Codeigniter. I want to fetch top 15 songs by number of downloads. To my knowledge, I got all unique ID's out ranging from highest to least. But now, I want to use each of these unique ID's to fetch data from another table in the database.
I have tried using for loop; but it seems to only return one of the rows which happens to be the first and highest number of occurrence in the array. The code below echo's the ID's but how can I use each of those ID's to fetch data.
function top15(){
$this->db->select('musiccode');
$result=$this->db->get('downloads');
$query = $result->result_array();
$downloads = array();
if(!empty($query)) {
foreach($query as $row)
{
$musiccode[] = $row['musiccode'];
}
$mode = array_count_values($musiccode);
arsort($mode);
$i = 0;
foreach ($mode as $field => $number) {
$i++;
echo $field." occured ". $number." times <br>";
if ($i == 15) {
break;
}
}
}
}
for ($b=0; $b < count($field); $b++) {
$this->db->where(array('track_musiccode'=> $field));
$field = $this->db->get('tracks');
return $field->result_array();
}
The code above only produce one row for me. I expect to have more than one and according to the number of ID's in the array. Thanks in advance.
For a single column condition, you could use where_in() instead and drop the for loop :
$this->db->where_in('track_musiccode', $field);
$field = $this->db->get('tracks');
return $field->result_array();
Yes Finally i did it. Incase if anyone needs it. this works just fine
function top15(){
$this->db->where('d_month', date('m'));
$this->db->select('musiccode');
$result=$this->db->get('downloads');
$query = $result->result_array();
$downloads = array();
if(!empty($query)) {
foreach($query as $row){
$musiccode[] = $row['musiccode'];
}
$res='';
$count=array_count_values($musiccode);
arsort($count);
$keys=array_keys($count);
for ($i=0; $i < count($keys); $i++) {
$res[] .= "$keys[$i]";
}
$this->db->where_in('track_musiccode', $res);
return $this->db->get('tracks')->result_array();
}
}
And I got this too. If I wasn't going to count occurrences but just iterate the number of downloads which is far more better than counting in other not to over populate the database and make your website work slowly.
function top15(){
$tracks = '';
$this->db->group_by('counter');
$result=$this->db->get('downloads');
$query = $result->result_array();
$counter = '';
$fields = '';
if(!empty($query)) {
foreach($query as $row) {
$counter[] = $row['counter'];
}
rsort($counter);
for ($i=0; $i<=15; $i++) {
$this->db->where('downloads.counter', $counter[$i]);
$this->db->join('tracks', 'tracks.musicid = downloads.musicid');
$fields[] = $this->db->get('downloads')->row_array();
}
return $fields;
}
}
Enjoy...

Get array data and insert into database

I'm trying to get the data in the array that came from another function(that function is extracting the data in the csv file) and when i tried calling the two fields from that array it shows an error that it is unidentified variables.
The $this->csv_process(); as shown on the function action() is the function that extracts the data from the csv file and stores it in an array which is successful since I tried checking it on var_dump();
I also named the two fields as $name and $email as shown below:
Function CSV_process()
public function csv_process()
{
/* variables for openning the csv file */
if (!in_array($extension, $allowed_ext)) {
$this->session->set_flashdata("message", "Sorry, CSV file only.");
} else {
if ($filesize > 0) {
$file = fopen($filename, "r");
$toWrite = array();
$error = false;
$col_size = 2;
$skip = 0;
while ($data = fgetcsv($file, 10000, ","))
{
$skip++;
if ($skip == 1) {
continue;
}
$numofcol = count($data);
if ($numofcol != $col_size ) {
$this->session->set_flashdata("message", "Column count exceeded or missing.");
} else {
$name1 = $data[0];
$name = str_replace("'", "''", $name1);
$email1 = $data[1];
$email = str_replace("'", "''", $email1);
$toWrite[] = [
'name' => $name,
'email' => $email
];
}
}
}
}
return $toWrite;
}
Function Action()
function action(){
$toWrite[] = $this->csv_process();
foreach ($toWrite as $arr) {
list($name, $email) = $arr;
//die(var_dump($arr));
$query = $this->db->query("SELECT * FROM import WHERE name ='$name' AND email = '$email'");
if ($query->num_rows() >= 1) {
} else {
if ($name == "" OR $email == "") {
} else {
if ((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE ) {
} else {
$this->db->query("INSERT INTO import(name, email, created_date) VALUES('".$name."', '".$email."', '".date("Y-m-d h-i-s")."')");
$this->session->set_flashdata('message', 'SUCCESS YEAY');
redirect('Clean_csv/index');
}
}
}
$query->free_result();
}
}
Listing arrays doesn't seem to work for here, anyone knows how to extract the data array from $arr?
You don't need to extract the values. You can use each $arr in a bound query. It simplifies the syntax for the select query.
For inserting use CodeIgniter's insert() method. Again, the $arr can be used directly by adding the date to it before the insert is attempted.
I think this will work.
function action()
{
$toWrite[] = $this->csv_process();
foreach($toWrite as $arr)
{
$query = $this->db->query("SELECT * FROM import WHERE name=? AND email=?", $arr);
if($query->num_rows() >= 1)
{}
else
{
if($arr['name'] == "" OR $arr['email'] == "")
{}
else
{
if((filter_var($email, FILTER_VALIDATE_EMAIL)) == FALSE)
{}
else
{
$arr['created_date'] = date("Y-m-d h-i-s");
$this->db->insert("import", $arr);
$this->session->set_flashdata('message', 'SUCCESS YEAY');
//??? redirect('Clean_csv/index');
//Are you sure, you may still have more $arr in $toWrite to process - right?
}
}
}
$query->free_result();
}
}
You need to know what a terrible idea it is to repeatedly run database queries inside a loop. Even though you use free_result() it could be a massive drain on server resources. If your csv file has several thousand items you are severely stressing the database and the server.

CakePHP 2.5 Datasource, create and return response

I have a specific task to connect CakePHP web application to a remote restful server . I create a datasource, read method works great, but the api after save data return an array of processed data.
Looking for a way to return the data array and use in controller.
My Controller code
public function admin_generate()
{
$data = $this->request->data;
$data['path'] = 'special/generate';
$this->Tool->create();
if($this->Tool->save($data)){
// handle response ????
}
$this->set('data',$data);
$this->set('_serialize','data');
}
In datasource file
public function create(Model $model, $fields = null, $values = null)
{
$data = array_combine($fields, $values);
$api = $this->config['api_path'].$data['path'].'?auth_key='.$this->config['auth_key'];
$json = $this->Http->post($api, $data);
$response = json_decode($json, true);
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
return $response; // ??????
}
Can someone show me the correct way to use the api response data in the controller?
I found a solution, a few minutes after a post question. This can help one of you.
datasource
....
if (is_null($response)) {
$error = json_last_error();
throw new CakeException($error);
}
// SOLUTION
$model -> code = $response['code'];
$model -> key = $response['key'];
$model -> code_id = $response['code_id'];
return true;
.....
in controller
.....
if($this->Tool->save($data)){
unset($data['path']);
$data['code'] = $this->Tool->code;
$data['key'] = $this->Tool->key;
$data['code_id'] = $this->Tool->code_id;
}
.....

using same array in different functions

Here's the situation: I have 2 different functions and one view. I need to send data from function 1 to the view (2 arrays), and from that view i need to send data to function 2 (1 array).
Sending data from function 1 to the view is an easy job, but i don't know how to do it with function 2 because the information i would like to send to it has a function 1's array plus other new data the users entry.
I know there's no chance to send an array through URL, but i'm out of ideas.
Which is the best option for passing the data?
i send to the view this data:
admin: (part of the function 1)
//last part of the code
$this->data['conditions'] = $conditions;
$this->data['notselectedconditions'] = $notselectedconditions;
$this->parser->parse('admin/tools/showReport.tpl',$this->data);
In the view i use the information on those arrays, and user can put some new entry.
view:
<dt>Tipo de Usuario<dt>
<dd>Pre Registrado</dd>
reloadConditions is function 2, the one that needs what function 1 provides plus the selection of the user in order to keep filtering the results.
The information i need to have available on function 2 is: array 'conditions' and users new entry
After a long discussion and some clarifications in chat, here is the solution I came up with:
<?php
function addQueryParameters($url, $params) {
$paramsStr = http_build_query($params);
$fragment = parse_url($url, PHP_URL_FRAGMENT);
$query = parse_url($url, PHP_URL_QUERY);
$interUrl = '';
if ($query === NULL) {
$interUrl = '?';
}
if ($fragment !== NULL) {
$interUrl = '&';
}
$interUrl .= $paramsStr;
if ($fragment !== NULL) {
$pos = strpos($url, '#' . $fragment);
$url = substr($url, 0, $pos) . $interUrl . substr($url, $pos);
}
return $url;
}
function linkifyFilterConditions($url, $conditions) {
return addQueryParameters($url, array('conditions' => $conditions));
}
// Tests
// TODO: replace by unit tests
var_dump(linkifyFilterConditions('http://example.com/blub', [1,2,3]));
var_dump(linkifyFilterConditions('http://example.com/blub#a', [1,2,3]));
var_dump(linkifyFilterConditions('http://example.com/blub?a=b#a', [1,2,3]));
Usage (in OP's views):
$href = 'yourscript?conditions[]=a';
$href = linkifyFilterConditions($href, $conditions);
echo '<a href="' . $href . '">Test</>';
How about puting you arrays in $_SESSION?
see here http://www.phpriot.com/articles/intro-php-sessions/7

codeigniter multiple table joins

function in codeigniter model is not working. I'm getting http error 500 because of below code in codeigniter model function. if I remove this code.. code is working fine.
function get_ad_by_user($a,$b)
{
$this->db->select('title,ci_categories.category,ci_subcategories.subcategory,state,city,locality,ad_website,description,phone_number,address,image_token1,image_token2');
$this->db->from('ci_pre_classifieds');
$this->db->join('ci_categories', 'ci_categories.category_id = ci_pre_classifieds.category');
$this->db->join('ci_subcategories', 'ci_subcategories.subcategory_id = ci_pre_classifieds.sub_category');
$this->db->where('ci_pre_classifieds.id',$a);
$this->db->where('ci_pre_classifieds.ad_string_token',$b);
$q=$this->db->get();
$this->db->last_query();
log_message('debug','******query'.$this->db->last_query().'********');
if($q->num_rows()==1)
{
foreach($q->result_array() as $row)
{
$data['title]=$row['title'];
$data['category']=$row['ci_categories.category'];
$data['sub_category']=$row['ci_subcategories.subcategory'];
$data['state']=$row['state'];
$data['locality']=$row['locality'];
$data['ad_website']=$row['ad_website'];
$data['description']=$row['description'];
$data['phone_number']=$row['phone_number'];
$data['address']=$row['address'];
}
}
else
{
$data['message']="sorry either classified expired or deleted";
}
return $data;
}
I'm getting error in for each block..if I remove everything working...How to copy $row array in $data array
$data['title]=$row['title']; has a ' missing.
This could be the reason but without that error message, it's hard to tell.
Also, you may want to reduce the function to the following:
function get_ad_by_user($a,$b)
{
$data = array();
$this->db->select('title,ci_categories.category,ci_subcategories.subcategory,state,city,locality,ad_website,description,phone_number,address,image_token1,image_token2');
$this->db->from('ci_pre_classifieds');
$this->db->join('ci_categories', 'ci_categories.category_id = ci_pre_classifieds.category');
$this->db->join('ci_subcategories', 'ci_subcategories.subcategory_id = ci_pre_classifieds.sub_category');
$this->db->where('ci_pre_classifieds.id',$a);
$this->db->where('ci_pre_classifieds.ad_string_token',$b);
$q=$this->db->get();
log_message('debug','******query'.$this->db->last_query().'********');
if($q->num_rows()==1)
{
$data[] = $q->row_array();
}
else
{
$data['message']="sorry either classified expired or deleted";
}
return $data;
}
If you are only returning one row in your query, you can simply use $q->row_array() or $q->row() to return the single row.
Just in case, I would also declare $data = array() at the start of your get_ad_by_user function, otherwise it "could" complain that $data does not exist.

Resources