how to sort a dataset in PHP? - php

I am using PDO to connect to my tables in the database. So I wrote a quick function to return the results that was return from the data table. Yes I can use SORT BY in my query to sort the results but i want to avoid that in this query because this query pull information for a large table.
* First I need to be able to sort this data set at the user end. so I need somehow to sort by different columns so I can sort by column "fullName" or sort by "userID" or "createdDate"
so when PDO fetch the results and return the array I want to sort those.
* Second question where in this function I do a free results or do I free them outside the query?
function getDataSet($query, $connection){
$cmd = $connection->query( $query );
return $cmd->fetchAll(); //PDO::FETCH_ASSOC
}
then I can call this function by simply doing
$dataset = getDataSet("select * from users", $db)
in my first question i want to sort $dataset.

I do NOT agree with you on not using "ORDER BY" in your SQL statement. But anyway, you can try this:
$tmp_dataset = array();
foreach($dataset as $data)
{
$tmp_dataset[ $data['name_of_column'] ] = $data;
}
$dataset = $tmp_dataset;
ksort($dataset);

Related

Fetch featured product only from product table in Api

Product Table
where i want to fetch only featured product. I have defined a column in database product_type in which four types of products(hot deals, newly listed, deals of the day and featured product)strong text can be listed which is optional.
Blockquote
Here is my model|query code in codeigniter
public function featured_product()
{
$arrResult = array();
$this->db->select('*');
$this->db->from('product');
$this->db->where("product_type","featured");
$result = $this->db->get()->result_array();
if(!empty($result))
{
$arrResult['result'] = $result;
}
else
{
$arrResult['result'] = '';
}
return $arrResult ;
}
When i try to fetch whole product list in api i get the result but i want to show only featured product.
You could try and use find_in_set:
https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_find-in-set
I don’t know codeigniter, but I think, this looks useful:
https://forum.codeigniter.com/thread-71337.html
I propose a different approach.
This is not an answer to your question, but I hope it will allow you to rethink your table structure.
Instead of storing all the product_types in a single column use a pivot table (also known as a junction table).
You'll want to store all the data that you currently have in product_types column in a separate table(the pivot, lets call it product_to_type) and reference the id of product_table and product_type in the pivot table.
Something like this:
Here's a nice db-fiddle to play around with if you want.
This has multiple advantages:
You have a atomic tables
You can add data to either table without causing trouble in other tables
Foreign key ensure data consistency(you can probably do a better job with that. The keys are used are decent but not great)
You can extract any sort of data with the correct use of joins
You can add indexes to make the query buttery smooth
I'm sure there are other advantages too.
As I have changed my database to separate table with product_id matching with product_type. Still I find the solution to my question with a function FIND_IN_SET().
Here is my updated modal query:
public function featured_product()
{
$arrResponse = array();
$data = 'featured';
$this->db->select('*');
$this->db->where('find_in_set("'.$data.'", product_type) <> 0');
$this->db->from('product');
$result = $this->db->get()->result_array();
if(!empty($result))
{
$arrResponse['result'] = $result;
}
else
{
$arrResponse['result'] = '';
}
return $arrResponse ;
}

How to perform a calculation on a row basis and SUM on laravel

I have a situtaion where I have data in two columns in a table, which need to be multiplied on a row basis. Then each value from the multiplication has to be added to provide a net result
I tried this but it does not work
public function getCampaignStats($item)
{
$query = CampaignStats::where('item',$item);
foreach($query as $q) {
$q->p_c;
$q->caa;
dd($q->p_c);
}
return $query;
}
I get this exception when i try to do this
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
Is there a better way to do this foreach loop in laravel
You can use raw queries for such a case and do the math within your query. Have a look at the docs:
https://laravel.com/docs/5.4/queries#raw-expressions
https://laravel.com/docs/5.4/queries#where-exists-clauses

Cannot retrieve single column from database. Laravel

I'm trying to retrieve single column from my table grades.
For that I have used following code in my controller:
public function verify($id,$sid)
{
$grade=Grade::all('annual')->whereLoose('id',$id);
return $grade;
}
Where, annual is column name. But it is returning empty set of array [].
all() takes a list of columns to load from the database. In your case, you're fetching only one column called annual, therefore filtering on id later on does not return results. Replace your code with the following and it should work:
$grade = Grade::all('id', 'annual')->whereLoose('id', $id);
Keep in mind that it will return a collection of objects, not a single object.
NOTE: you're always loading all Grade objects from the database which is not efficient and not necessary. You can simply fetch object with given id with the following code:
$grade = Grade::find($id); // fetch all columns
$grade = Grade::find($id, ['id', 'annual']); // fetch only selected columns
The code you are using is loading all rows from the grades table and filtering them in code. It is better to let your query do the filter work.
For the columns part, you can add the columns you need to the first() function of the query, like so:
public function verify($id,$sid)
{
$grade = Grade::where('id', $id)->first(['annual']);
return $grade->annual;
}

Select MySQL If (ID) In Array

So I trying to build a notification system (CodeIgniter) and not store it in my database by this unique ID. Now I got some problem to using `SELECT query.
Also this is array stored in "value" row:
[{"id":0,"user_id":"1","comment":"That's a Nice Video.","posttime":1403523177,"status":1},{"id":1,"user_id":"4","comment":"Nice to see this..!!","posttime":1403590409,"status":1}]
And this is my (not work) query:
$query = $this->db->get_where('post_meta',array('status'=>1),in_array('user_id', $id));
Ideas?
Note: Notification will be sparated by "user_id".
You should not use in_array('user_id', $id) on that function because it returns boolean.
On the active record page: https://ellislab.com/codeigniter/user-guide/database/active_record.html you can take a look at parameter it takes for get_where() function
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
Notice how the third parameter takes $limit which talks about the number of data you'll receive. (Leaving this blank will return you all data).
Some code examples:
If you just want to get the data with status = 1, use the following:
$query = $this->db->get_where('post_meta',array('status'=>1));
If you want to get the data with status = 1 and user_id = $id, use the following:
$this->db->like('value', '"user_id":"'.$id.'"');
$query = $this->db->get_where('post_meta',array('status'=>1));
The solution above is not the best, but it should work.
The $this->db->like() function will create rules to get data in value row which has "user_id":"$id" where $id is the value that you define.
What if I want to get all notifications and group them based on their ID?
I usually get all the data and then use PHP to group them into its own array. I think it's cheaper than relying on database to do that (Correct me if i'm wrong).
So use the first code:
$query = $this->db->get_where('post_meta',array('status'=>1));
Then iterate them using foreach() or whatever you find convenient.
$data = array();
foreach($query as $k=>$v) {
// Run a function to get User ID
$user_id = your_function_here($v->value);
if(!isset($data[$user_id]))
$data[$user_id] = array();
// This is just some example to group them together, you can optimize it to your own liking
array_push($data[$user_id],$v);
}
your_function_here() is your function to get the user_id from value row on your database.

Codeigniter alter query

I'm building a search function and i'm pretty sure the proper way is to only get the # of results you want to display, in my case 20 per page. I'm wondering what is the best way for me to change that select('*') statement to return the total # of results select('count(*)'); and rerun the exact same query?
$this->db->select('*');
$this->db->from('MyTable');
$this->db->where('some complex conditions');
$this->db->join('a bunch of joins);
$this->db->limit('20','$page*20');
to
$this->db->select('count(*)');
/* reuse this part */
$this->db->from('MyTable');
$this->db->where('some complex conditions');
$this->db->join('a bunch of joins);
/* reuse this part */
run first query
$q1 = $this->db->get()->result_array();
run second query
$q2 = $this->db->get('q1 with different select')->result_array();
array_merge($q1,$q2);
Codeigniter actually has a pagination helper that is pretty useful:
https://ellislab.com/codeIgniter/user-guide/libraries/pagination.html
If you don't prefer to use it, you can pass in the current query number that you are at to the controller through the url.For example www.example.com/page/search/40. Where the query will then take that number to use for the limit.
You Can also do this way
// For required output
$this->db->select('');
$this->db->from();
$this->db->join();
$this->db->order_by();
$this->db->limit((int)$page['limit'],(int)$page['start']);
$list['list'] = $result->result();
// To count total number of rows
$this->db->select('');
$this->db->from();
$this->db->join();
$this->db->order_by();
$result_total = $this->db->get();
$list['list'] = $result->result();
$list['total'] = $result_total->num_rows();
return $list;
}

Categories