CodeIgniter - unable to query database - codeigniter

I have written a function, and it's working except one part:
//Find current upload total value
$this->EE->db->select('upload_total');
$upload_total = $this->EE->db->get_where('exp_competition_purchase_upload_total', array('member_id' => $member_id));
return $upload_total->result();
// If upload total is more than 0
if($upload_total > 0) {
$new_total = $upload_total + $my_data['upload_total'];
$my_data['upload_total'] = $new_total;
}
Can anyone tell me if they can see any issue with this particular part of the code?
Here is the full function. It runs in an extension. The extension is working, it just appears to be the above code that isnt.
I am basically just trying to find the value in the db, then if the value is more than one, add the value to another.
function cartthrob_on_authorize()
{
foreach ($this->EE->cartthrob->cart->items() as $item) {
// Create array to store member id and purchased upload slots
$my_data = array(
'member_id' => $this->EE->session->userdata('member_id'),
'upload_total' => $item->item_options('fees'),
);
// Store member id in variable
$member_id = $my_data['member_id'];
// Query table to check if there is record with member id exists
$query = $this->EE->db->get_where('exp_competition_purchase_upload_total', array('member_id' => $member_id));
// If query returns more than 0 update record
if($query->num_rows() > 0) {
//Find current upload total value
$this->EE->db->select('upload_total');
$upload_total = $this->EE->db->get_where('exp_competition_purchase_upload_total', array('member_id' => $member_id));
// If upload total is more than 0
if($upload_total > 0) {
$new_total = $upload_total + $my_data['upload_total'];
$my_data['upload_total'] = $new_total;
}
return $upload_total->result();
$this->EE->db->where('member_id', $member_id);
$this->EE->db->update('exp_competition_purchase_upload_total', $my_data);
// If query returns 0 insert new record
} else {
$this->EE->db->insert('exp_competition_purchase_upload_total', $my_data);
}
}
}

//Find current upload total value
$this->EE->db->select('upload_total');
$upload_total = $this->EE->db->get_where('exp_competition_purchase_upload_total', array('member_id' => $member_id))->result_array();
$upload_total = $upload_total[0];
//If upload total is more than 0
$upload_total_col = $upload_total['upload_total']>0 ? $upload_total['upload_total']:0;
$my_data['upload_total'] += $upload_total_col;
From what I understand you, just want to increment upload_total.
Note: Don't use return $upload_total->result(); in between your function without putting a condition.

result of query is not an integer, it is an object
try like this;
//Find current upload total value
$this->EE->db->select('upload_total');
$upload_total = $this->EE->db->get_where('exp_competition_purchase_upload_total', array('member_id' => $member_id));
$result = $upload_total->result();
// If upload total is more than 0
if($upload_total->num_rows() > 0) {
$my_data['upload_total'] += $result->upload_total;
}
return $my_data;
btw, I'm not sure what you want to do, so i just corrected it!

here is the solution
$this->EE->db->select('upload_total');
$upload_total = $this->EE->db->get_where('exp_competition_purchase_upload_total', array('member_id' => $member_id));
// If upload total is more than 0
if($upload_total->num_rows() > 0) {
$result = $upload_total->row_array();
$new_total = $result['upload_total'] + $my_data['upload_total'];
$my_data['upload_total'] = $new_total;
}
return $my_data;
try that. it was becuase u was trying to use the DB returned object as an int.

Related

Display large array in laravel blade in too much time

so i got imported my large excel file with huge informations with 1 sec and i did get all the information i need to display within 1 sec to , but i got a big probleme when displaying the array in the view coz i m testing if the cells are correct or not i m using 5 ifs and 3 foreach and it takes mote than 2 mins , i need help to display all the info in a short time this is my array , and thanks
and there is my code of the view which takes to much time to display infos
and thanks
//here we get our final result of true and false fields
$finale_array = [];
// here we get all our
$current_table2 = [];
$results_applied = [];
$current_result = [];
$columns = SCHEMA::getColumnListing('imports');
// here we get all our conditions
$conditions = DB::table('conditions')->select('number', 'field', 'value')->get();
// here we get all our data
$imports = DB::table('imports')->get();
$results = DB::table('results')->get();
$x = 0;
$default_value = 0;
foreach ($imports as $key => $imported) {
$res = get_object_vars($imported);
foreach ($conditions as $value) {
$array = get_object_vars($value);
$result = $this->test($columns, $array['field']); // the result of our test function
if ($result == "ok") {
if ($res[$array['field']] == $array['value']) {
foreach ($results as $value_result) {
$res_resultat = get_object_vars($value_result);
$test_field = $this->test($columns, $res_resultat['field']);
// testing if the condtion numder match with the result number
if (($res_resultat['condition_number'] == $array['number'])) {
if (($test_field == 'ok')) {
if ($res['id'] != $default_value) {
// here test if the difference between the id and the default value is different from the current id to insert
if (($res['id'] - $default_value) != $res['id']) {
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
$current_table2 = [];
$results_applied = [];
$default_value = $res['id'];
}
$current_table2 = [$res, $res['id']];
}
$current_result = [$res_resultat['field'], $res[$res_resultat['field']]];
if ($res_resultat['value'] == $res[$res_resultat['field']]) {
$current_result[2] = 'true';
$current_result[3] = $res_resultat['value'];
} else {
$current_result[2] = 'false';
$current_result[3] = $res_resultat['value'];
}
$current_result[4] = $array['number'];
array_push($results_applied, $current_result);
}
}
}
}
}
}
$default_value = $res['id'];
}
array_push($current_table2, $results_applied);
array_push($finale_array, $current_table2);
dd($finale_array);
return view('Appliedconditions', ['imports' => $finale_array, 'columns' => $columns]);
}
From what I can see, you are recovering all the data without paging it.
You must paginate the data using the paginate(#elements_per_page) directive in your query, where #elements_per_page is the number of elements you want to display per page.
For example:
$elements = Elements::select('*')->paginate(10);
and in your blade view you can retreive pagination links after the closing table tag in this way: {{ $elements->links() }}

How to use and display PagedResultDto

Using ASPNet Boilerplate, and returning a pagedResultSetDto with the below code, how do I display the page links?
public PagedResultDto<ArticleDto> GetAll()
{
var articleCount = articleRepository.Count();
var t = articleRepository.GetAllIncluding(x => x.articleImage).Include(x => x.Category).Where(
x => x.PublishFrom <= DateTime.Now &&
x.PublishTo >= DateTime.Now &&
x.Status == PostStatus.Published &&
x.IsDeleted == false
).OrderByDescending(x=> x.PublishFrom).ToList();
return new PagedResultDto<ArticleDto>
{
TotalCount = articleCount,
Items = t.MapTo<List<ArticleDto>>()
};
}
First, take in IPagedResultRequest as input:
// using Abp.Linq.Extensions;
public PagedResultDto<ArticleDto> GetAll(PagedResultRequestDto input)
{
var articleCount = articleRepository.Count();
var t = articleRepository
.GetAllIncluding(x => x.articleImage)
.Include(x => x.Category)
.Where(x =>
x.PublishFrom <= DateTime.Now &&
x.PublishTo >= DateTime.Now &&
x.Status == PostStatus.Published &&
x.IsDeleted == false
)
.OrderByDescending(x => x.PublishFrom)
.PageBy(input) // Page by SkipCount and MaxResultCount
.ToList();
return new PagedResultDto<ArticleDto>
{
TotalCount = articleCount,
Items = t.MapTo<List<ArticleDto>>()
};
}
Then create your own links to pass in SkipCount, e.g. GetAll?SkipCount=10 for page 2.
MaxResultCount has a default value of 10.
You can calculate it according to the result of GetAll().
You request how many records you want. Let's say 10 (default value).
It returns TotalCount and Items (=records). Let's say TotalCount = 95. Divide 95/10 = 9.5 ~=> 10 pages. Show 10 links. While 9 pages will show 10 records, last page will have 5 records. That

Laravel 5.3 database transaction issue?

I have used more time with Laravel 5.0 on database transaction but when I change to Laravel 5.3.* it not work as I want even I have disabled commit() method all data still continue insert into database.
if ($request->isMethod('post')) {
DB::beginTransaction();
$cats = new Cat();
$cats->parent_id = $this->request->input('category_id');
$cats->status = ($this->request->input('status')) ? $this->request->input('status') : 0;
if ($res['cat'] = $cats->save()) {
$catD = new CategoryDescriptions();
$catD->category_id = $cats->id;
$catD->language_id = 1;
$catD->name = $this->request->input('en_name');
if ($res['cat2'] = $catD->save()) {
$catD2 = new CategoryDescriptions();
$catD2->category_id = $cats->id;
$catD2->language_id = 2;
$catD2->name = $this->request->input('kh_name');
$res['all'] = $catD2->save();
}
}
if ($res) {
//DB::commit();
return $res;
}
return [false];
}
Check this line ($res['cat'] is a boolean):
if($res['cat'] = $cats->save()) {
And this ($res is an array. You compare an array as boolean!):
if($res){
The right condition should be:
$res = array(); // the first line of your method
// .... your http method check, start transaction, etc.
if (!in_array(false, $res, true)) { // check if array doesn't contain 'false values'
DB::commit();
}

Select from mulitle tables with count in Linq

I am busy with a small online voting web app, now I struggling to get the total number of votes for each party that I stored in a different table. Here is what I have tried, this method gets each party from the votes table named [dbo].[VoterCandidateMapping]
public List<int> GetAllPartIDs()
{
List<int> partieIDs = new List<int>();
var parties = (from votes in voteDB.VoterCandidateMappings
select votes.PartyID).Distinct().ToList();
partieIDs = parties;
return partieIDs;
}
Then I want to use this method to count each vote associated with a particular part, here is the code
public IQueryable<ResultsViewModel> GetResults()
{
int numberOfVotes = 0;
foreach (int IDs in GetAllPartIDs())
{
numberOfVotes = (from votes in voteDB.VoterCandidateMappings
where votes.PartyID == IDs ? true : false
select votes.VoterID).Count();
}
return (
from results in voteDB.VoterCandidateMappings
join parties in voteDB.Parties
on results.PartyID equals parties.Id
select new ResultsViewModel
{
PartyName = parties.Name,
TotalVotes = numberOfVotes
});
}
It runs and return almost every data but the total number of votes is the same
The reason why it does not work is that you are trying to store multiple values in a single numberOfVotes variable.
Let's go through code what you have now.
First foreach loop calculate votes for each party and assigns to numberOfVotes variable. Each time value is assigned, existing value in numberOfVotes is overwritten. In the end of loop numberOfVotes contains number of votes for the last party. This is value you are seeing in your results as you use the same variable to return results.
Here is one way to do it correctly:
public IQueryable<ResultsViewModel> GetResults()
{
var groupedVotes = voteDB.VoterCandidateMappings
.GroupBy(x => x.PartyID)
.Select(x => new { PartyId = x.Key, NumberOfVotes = x.Count());
return voteDB.Parties
.Select(x => new ResultsViewModel
{
PartyName = x.Name,
TotalVotes = groupedVotes
.Where(y => y.PartyId == x.Id)
.Select(y => y.NumberOfVotes)
.FirstOrDefault()
});
}

LINQ in Business Layer paging / sorting gridview in User layer

I have a gridview in my user layer that uses a business layer method as its datasource, and I want the gridview to support paging and sorting. When I returned an Ienumerable from the method, it will bring back all of the data. If I use Take/Skip to bring back only a page's worth, the gridview doesn't realize that there are many pages of data.
When I change the Ienumerable to an IQueryable, the DataBind() fails because the data has already been disposed of. I think this problem has something to do with when the query actually executes and it may have to do with the filters I am applying to the query (see below).
User Layer Code:
grdSelectedQuestionaires.DataSource = assessment.FilteredAssessmentList(filter);
grdSelectedQuestionaires.DataBind(); <-- Fails - "Cannot access a disposed object"
Business Layer Code:
public IQueryable<Assessment> FilteredAssessmentList(AssessmentSearchFilter filter)
{
using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
{
var rows = (
from a in dc.vPAQSummaries
select new Assessment()
{
PAQNumber = a.PAQNumber.Trim(),
CustomerID = (int)a.CustomerID,
Department = a.Department.Trim(),
CustomerName = a.CustomerName.Trim(),
DOTNumber = a.DOTNumber.Trim(),
OrgName = a.OrgName.Trim(),
DateEntered = a.DateEntered,
GroupNumber = a.GroupNumber.Trim(),
JobTitle = a.JobTitle.Trim(),
FileNames = a.FileNames.Trim(),
AnalystType = a.AnalystType.ToString(),
Incumbents = a.Incumbents,
});
// Filter by Customer ID
if (filter.CustomerID > 0)
{
rows = rows.Where(r => r.CustomerID == filter.CustomerID);
}
else
{
rows = rows.Where(r => r.CustomerID != null);
}
// Filter by DOT Number
if (!string.IsNullOrEmpty(filter.DOTNumberFrom))
{
if (string.IsNullOrEmpty(filter.DOTNumberTo))
{
rows = rows.Where(r => r.DOTNumber == filter.DOTNumberFrom);
}
else
{
rows = rows.Where(r => r.DOTNumber.CompareTo(filter.DOTNumberFrom) >= 0
&& r.DOTNumber.CompareTo(filter.DOTNumberTo) <= 0);
}
}
// Filter by OrgName
if (!string.IsNullOrEmpty(filter.OrgName))
{
rows = rows.Where(r => r.OrgName.StartsWith(filter.OrgName));
}
// Filter by Group
if (!string.IsNullOrEmpty(filter.GroupNumberFrom))
{
if (!string.IsNullOrEmpty(filter.GroupNumberTo))
{
rows = rows.Where(r => r.GroupNumber == filter.GroupNumberFrom);
}
else
{
rows = rows.Where(r => r.GroupNumber.CompareTo(filter.GroupNumberFrom) >= 0
&& r.GroupNumber.CompareTo(filter.GroupNumberTo) <= 0);
}
}
if (filter.Skip > 0)
{
rows = rows.Skip(filter.Skip);
}
if (filter.Take > 0)
{
rows = rows.Take(filter.Take);
}
else
{
rows = rows.Take(100);
}
return rows.Distinct();
}
}
}
The paging problem was caused by the Using statement. Changing this:
using (PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext())
{
...
}
to this:
PAQcDataLayerDataContext dc = new PAQcDataLayerDataContext();
Made paging work. Now I have to figure out how sorting works.

Resources