Query Improvement: foreach - php

I have the following model function and I was wanting to know how I could improve it and also pull the needed $row out when needed so that I dont get a PHP error.
How I am pulling the required data:
$data['companyName'] = $this->core_model->companyDetails('coreCompanyName');
Errors:
Undefined property: stdClass::$coreContactName
Undefined property: stdClass::$coreContactEmail
Model:
function companyDetails()
{
$this->db->select('coreCompanyName, coreContactName, coreContactEmail');
$this->db->from('core');
$whereData = array('coreCompanyName' => $companyName, 'coreContactName' => $companyContactName, 'coreContactEmail' => $companyContactEmail);
$this->db->where($whereData);
$query = $this->db->get();
$result = '';
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$result .= $row->coreCompanyName;
$result .= $row->coreContactName;
$result .= $row->coreContactEmail;
}
}
return $result;
}

It should be like this
$this->db->select('coreCompanyName, coreContactName, coreContactEmail');
not
$this->db->select('coreCompanyName','coreContactName','coreContactEmail');
See reference http://codeigniter.com/user_guide/database/active_record.html#select
To limit to a specific set of records, use the where() function. e.g.
$this->db->where('companyId', $companyId);

<?php
/**
*
* WHERE ARE : $companyName, $companyContactName, $companyContactEmail being defined ?
* WHY return 'companyName' WHEN You are quering based on the '$companyName' ???
* Your query wil fail with out it, that that's all your using ?
*
*/
function companyDetails() {
$query = $this->db->query("SELECT companyName FROM core WHERE coreCompanyName = ? AND coreContactName = ? AND coreContactEmail = ? LIMIT 1",
array($companyName, $companyContactName, $companyContactEmail));
return ($query->num_rows() == 1) ? $query->row()->companyName : FALSE;
}

Change:
$this->db->select('coreCompanyName','coreContactName','coreContactEmail');
To:
$this->db->select('coreCompanyName, coreContactName, coreContactEmail');
Now, you said this pulls all the data, but you aren't actually filtering the result. I wonder what the required data is

Related

Json returns a duplicate value using codeigniter

I am trying to fetch a data for each chkey with a related value as a group in codeigniter. When there are a 2 or more chkey then code is work properly.
But when there is a only 1 chkey then it shows value of that chkey but it is shows extra chkey:null,value:null in json.
Related json for chkey is 1 is as follows'
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"},{"chkey":"null","list":"null"}]}]
Expected is,
[{"unit_id":"8","CHGRAPHUpdatetime":{"time":"2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00,2018-03-15 00:00:00"},"channelGraph":[{"chkey":"ch1","list":"2,-30,12,20"}]}]
Could you please help me to resolve this issue.
model code-
public function chGraph($unitid){
$this->db->select("unit_id");
$this->db->from("device_unit");
$this->db->where('unit_id', $unitid);
$query = $this->db->get();
$unit = $query->result_array();
$j = 0;
foreach($unit as $row) {
$unit[$j]['CHGRAPHUpdatetime'] = $this->UnitCHGRAPHUpdatetime($row['unit_id']);
$unit[$j++]['channelGraph'] = $this->UnitCHGRAPHDetails1($row['unit_id']);
}
return $unit;
}
public function UnitCHGRAPHDetails1($unit_id)
{
$this->db->select('distinct(chkey)','chvalue');
$this->db->from('channel_info');
$query = $this->db->get();
$channelgraphData = $query->result_array();
$m = 0;
foreach($channelgraphData as $row) {
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .'';
$response = $this->db->query($chvalueQuery)->row();
$channelgraphData[$m++] = $response;
}
return $channelgraphData;
}
controller code-
public function chGraph()
{
$unitid = $this->uri->segment('3');
$GraphDetails = $this->device_model->chGraph($unitid);
echo json_encode($GraphDetails);
}
You could add a GROUP BY at the end of the statement to eliminate the null results :
$chvalueQuery = 'SELECT chkey, GROUP_CONCAT(chvalue)as list FROM channel_info where chkey= "'. $row['chkey'] .'" and unit_id='. $unit_id .' GROUP BY chkey';

sort varchar column codeigniter

i first checked if there any same problems like mine i ddnt find anything.
all are sorting alphanumeric column mixed with numeric data.
here is my problem.
i have a table that contain column A datas like this.
WRG-01 WRG-39 WRG-22 WRG-45 WRG-43
need to sort that as
WRG-01 WRG-22 WRG-39 WRG-43 WRG-45
this is the code i using so far in codeigniter frame work
$data['products'] = $this->db->order_by('product_id', 'asc')->get('products');
in mysql i can use this query to get done my work
preg_replace("/[^\d]/", "",'product_id'), 'asc')
How to apply it to my above codeigniter code?
here is search funtion
public function search()
{
$data['title'] = 'Search Product';
$product_name = $this->input->get('product_name');
$product_id = $this->input->get('product_id');
$product_category = $this->input->get('product_category');
$secondCategory = $this->input->get('secondCategory');
$thirdCategory = $this->input->get('thirdCategory');
$data['category'] = $this->db->order_by('id', 'asc')->get_where('categories', ['parent' => 0]);
if($product_category != '')
{
$data['secondCategory'] = $this->db->get_where('categories', ['parent' => $product_category]);
}
if($secondCategory != '')
{
$data['thirdCategory'] = $this->db->get_where('categories', ['parent' => $secondCategory]);
}
if($product_name != '')
{
$this->db->like('product_name', $product_name);
}
if($product_id != '')
{
$this->db->where('product_id', $product_id);
}
if($product_category != '')
{
$this->db->where('product_category', $product_category);
}
if($secondCategory != '')
{
$this->db->where('secondCategory', $secondCategory);
}
if($thirdCategory != '')
{
$this->db->where('thirdCategory', $thirdCategory);
}
$data['products'] = $this->db->order_by('product_id' 'asc')->get('products');
theme('all_product', $data);
}
i can't use sql query here because products is result array from product table.
Use MySQL cast
cast(product_id as SIGNED)
or
cast(product_id as UNSIGNED)
Try query like that :-
select * from products cast(product_id as UNSIGNED) ASC|DESC
Try this
$query= $this->db->query("SELECT * FROM products WHERE ??==?? ORDER BY product_id ASC");
$result= $query->result_array();
return $result;
as default data will sort by Ascending Order
This is in model. So if you pass it to controller it will return data as Objective Array.
So in controller you can access
$result = $this->model_name->method_for_above_code();
$name = $result[0]['name'];
$id = $result[0]['id'];
if in View
$result['this_for_view'] = $this->model_name->method_for_above_code();
foreach ($this_for_view as $new_item) {
echo "Name is ".$new_item['name'];
echo "ID is ".$new_item['id'];
}

Making simple allowed array in PHP? (CodeIgniter)

I have some simple function to collect allowed array, but something is not ok, can somebody help me? Here is my code
public function getAllbyLink($table, $what, $url)
{
$link=mysql_real_escape_string($url);
$query = $this->db->query("SELECT * FROM ".$table." WHERE ".$what." = '{$link}' LIMIT 0 , 1");
if ($query->num_rows() > 0)
{
return $query->result();
}
else redirect('');
}
Please read something about MVC pattern, question is clearly pointed on how to write a Model.
consider using this function
public function getTable($table, $where = array(), $select = '*', $order_by = '', $limit = '', $offset = '') {
if ($order_by !== '' && $order_by != 'RANDOM') $this->db->order_by($order_by);
if ($order_by == 'RANDOM') $this->db->order_by('id', 'RANDOM');
if ($limit !== '') $this->db->limit($limit, $offset);
$this->db->select($select);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
for your purpose call the function like this:
getTable($talbe, array('what' => $link));
//returns FALSE if no data are selected,
//or returns object with data,
if you wish return array instead replace $q->result() with $q->array_result()
Please note that active record auto escapes.
After comments:
comment-1, you can simplify that function easily just delete what you do not need, for example
public function getTable2($table, $where = array(), $limit = '', $offset = '') {
if ($limit !== '') $this->db->limit($limit, $offset);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
comment-2,when there is no data use this if-else statement
if (!$my_data = getTable2('table', array('where' => $link))) {
//there is some DATA to work with
echo "<pre>";
var_dump($my_data);
echo "</pre>";
} else {
//no DATA do redirect or tell user that there is no DATA
redirect(); //redirect to default_controller
}
comment-3, no comment;
comment-4, It also allows for safer queries, since the values are escaped automatically by the system. from this source. And another SO question about active record providing exact answer you are seeking.
My understanding of your code is:
Read all rows from table
Check if linkurl is in the list
If so, return a random row for that value
Else, redirect.
In this case, try this:
public function getAllbyLink($table,$url,$what)
{
$query = $this->db->query("
SELECT *
FROM `".$table."`
WHERE `".$what."` = '".mysql_real_escape_string($linkurl)."'
ORDER BY RAND()
LIMIT 1
");
if( !$query) return redirect('');
$result = $query->result();
if( !$result) return redirect('');
return $result;
}

Set Parameter with TableGateway Select Function show error undefined variable

i create a function in my model like :
public function getAllMenuByOnlyActionPage($actionlot){
$act = trim($actionlot);
$result = $this->tableGateway->select(function (Select $select) {
$select->where(array('status != ?' => 13))
->where(array('action' => $act))
->order('id ASC');
});
$results = array();
foreach ($result as $row) {
$results[] = $row;
}
return $results;
}
When i try to execute then its show me Notice: Undefined variable: act. I already see this link ZF2 tableGateway select but i want to set parameter for this function. Thanks
Try
$result = $this->tableGateway->select(function (Select $select) use ($act) {
$select->where(array('status != ?' => 13))
->where(array('action' => $act))
->order('id ASC');
});

select max codeigniter

Im trying to get an max value with codeigniter from an table but it isnt working. This is the error i get:
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to
string
Filename: database/DB_active_rec.php
Line Number: 427
This is my function:
public function getPeriodeNummer($bedrijf_id) {
$this->db->select_max('id');
$this->db->where('bedrijf_id', $bedrijf_id);
$result = $this->db->get('rapporten');
$this->db->select('periode_nummer');
$this->db->where('rapporten_id', $result);
$query = $this->db->get('statistieken_onderhoud');
$data = $query + 1;
return $data;
}
What im trying to do is as followed:
Select the highest id where bedrijf_id = $bedrijf_id from rapporten.
Select the periode_nummer from statistieken_onderhoud where rapporten_id = the highest id i got from step 1.
Add 1 to the periode_nummer i got from step 2 and return that number.
Thanks in forward for your help!
Try
public function getPeriodeNummer($bedrijf_id) {
$this->db->select_max('id');
$this->db->where('bedrijf_id', $bedrijf_id);
$res1 = $this->db->get('rapporten');
if ($res1->num_rows() > 0)
{
$res2 = $res1->result_array();
$result = $res2[0]['id'];
$this->db->select('periode_nummer');
$this->db->where('rapporten_id', $result);
$query = $this->db->get('statistieken_onderhoud');
if ($query->num_rows() > 0)
{
$row = $query->result_array();
$data['query'] = 1 + $row[0]['periode_nummer'];
}
return $data['query'];
}
return NULL;
}
Try this:
$this->db->select_max('display_sequence');
$this->db->from('acl_menu');
$query = $this->db->get();
$r=$query->result();
Display Sequence is your column name & acl_menu is your table name.
You can't use an object as a string. Use this:
public function getPeriodeNummer($bedrijf_id) {
$this->db->select_max('id');
$this->db->where('bedrijf_id', $bedrijf_id);
$result = $this->db->get('rapporten');
$this->db->select('periode_nummer');
$this->db->where('rapporten_id', $result);
$query = $this->db->get('statistieken_onderhoud');
// fetch first row in object
$result = $query->row();
$data = $result + 1;
return $data;
}
$this->db->select_max('id', 'max_id');
$query = $this->db->get('video_processing');
return $query->row();
try the above:
I think the $query variable is holding a mysql result resource and it cannot be used as a String or in this case an Integer.
You could try this way:
$data = mysql_result($query,0) + 1;
Shortest:
$this->db->select_max('id', 'max_id')->get('video_processing')->row();

Categories