i wasnt able to retrive fields from Joomla from 2 tables , the problem is the query return always 3 result but should return 2 result
public function getAgent(){
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select(array('ag.company_id','ag.first_name','ag.last_name'));
$query->from('#__cddir_agent AS ag');
$query->join('INNER','#__cddir_company AS c ON ag.company_id = c.id');
$data = $db->setQuery($query);
$result = $db->loadObjectList();
return $result;
}
can anyone tell me where is my issue
thanks
The query returns 3 because you are asking it to return 3 column fields in the line:
$query->select(array('ag.company_id','ag.first_name','ag.last_name'));
If you want to return 2 fields then ask it to return 2 column fields like
$query->select(array('ag.first_name','ag.last_name'));
Related
I am working in codeigniter, i have a below table of schemes, my problem is i want to show last updated data of each scheme. I dont know how to do that, please help.
my_table
scheme_code updated_on scheme_name
1 2015-04-13 One
3 2015-04-12 Three
4 2015-04-13 Four
3 2015-04-10 Three
3 2015-04-8 Three
1 2015-04-10 One
4 2015-04-11 Four
My Model
function show_last_updated_data(){
$this->db->select('*');
$this->db->from('my_table');
$this->db->order_by('updated_on', 'DESC');
$query = $this->db->get();
return $query->result();
}
Output Needed
scheme_code updated_on scheme_name
1 2015-04-13 One
3 2015-04-12 Three
4 2015-04-13 Four
My answer is based on #Syed Qarib. I modified it to be compatible with codeigniter active record format.
function show_last_updated_data() {
$this->db->select('*, str_to_date(updated_on, "%Y-%M-%d") As date', false); // false to skip escape
$this->db->from('scheme');
$this->db->group_by('scheme_code');
$this->db->order_by('date', 'DESC');
$query = $this->db->get();
return $query->result();
}
Edit
In another way,
function show_last_updated_data() {
$max = $this->db->select_max("updated_on")->group_by("scheme_code")->get('scheme')->result_array();
$updated_on = array();
if (count($max)) {
$updated_on = array_column($max, "updated_on"); // make sure your php version is >= 5.5
}
$this->db->select("*");
$this->db->from("scheme");
$this->db->where_in("updated_on", $updated_on);
$query = $this->db->get();
return $query->result();
}
Hope it will be useful for you.
Try this:
function show_last_updated_data(){
$this->db->select('*');
$this->db->from('my_table');
$this->db->group_by('scheme_name');
$this->db->order_by('updated_on', 'DESC');
$query = $this->db->get();
return $query->result();
}
You need to use group by it will retrieve your record based on scheme_code without repeating it and your desire results. :)
function show_last_updated_data() {
$query = $this->db->select('*')
->from('my_table')
->group_by('scheme_code')
->order_by('updated_on', 'DESC')
->get();
return $query->result();
}
As you have used custom date format, so the ordering will not work correctly until you convert the string to date format. Try this:
function show_last_updated_data(){
$this->db->select('*, str_to_date(updated_on, "%Y-%M-%d") date');
$this->db->from('my_table');
$this->db->order_by('date', 'DESC');
$query = $this->db->get();
return $query->result();
}
Note: It is recommended to use native date/datetime field, do not use custom formats. You can also go for UNIX timestamp and save it in an int field. As the date can be fetched in any format afterwards and will save you hassle like this one.
Can somebody help me convert this Sql Query
SELECT *
FROM customer c
LEFT JOIN customer_order co
ON c.customer_number = co.customer_number
AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid'
AND c.order_status = 'unserve'
AND co.cus_ord_no IS null
into Codeigniter query just like the image below for example
When query statements do not have clauses that need to change conditionally then using $this->db-query() is the way to go.
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co
ON c.customer_number=co.customer_number AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid' AND c.order_status='unserve' AND co.cus_ord_no IS null";
$query = $this->db->query($sql)->result();
echo json_encode($query);
It might be wise to include a check on the return from query() though because if it fails (returns false) then the call to result() will throw an exception. One way that can be handled is like this.
$query = $this->db->query($sql);
if($query !== FALSE)
{
echo json_encode($query->result());
return;
}
echo json_encode([]); // respond with an empty array
Query Builder (QB) is a nice tool, but it is often overkill. It adds a lot of overhead to create a string that literally is passed to $db->query(). If you know the string and it doesn't need to be restructured for some reason you don't need QB.
QB is most useful when you want to make changes to your query statement conditionally. Sorting might be one possible case.
if($order === 'desc'){
$this->db->order_by('somefield','DESC');
} else {
$this->db->order_by('somefield','ASC');
}
$results = $this->db
->where('other_field', "Foo")
->get('some_table')
->result();
So if the value of $order is 'desc' the query statement would be
SELECT * FROM some_table WHERE other_field = 'Foo' ORDER BY somefield 'DESC'
But if you insist on using Query Builder I believe this your answer
$query = $this->db
->join('customer_order co', "c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared')", 'left')
->where('c.customer_status','unpaid')
->where('c.order_status','unserve')
->where('co.cus_ord_no IS NULL')
->get('customer c');
//another variation on how to check that the query worked
$result = $query ? $query->result() : [];
echo json_encode($result);
You can do
public function view_customers()
{
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co ON c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared') WHERE c.customer_status='unpaid' AND c.order_status = 'unserve' AND co.cus_ord_no IS null";
return $this->db->query($sql)->result();
}
You can use row() for one output to object, or row_array() if one output but array. result() is multiple objects and result_array() is multiple arrays.
My way do usually is like this:
Controller:
public function view()
{
$this->load->model('My_Model');
$data = new stdclass;
$data->user_lists = $this->my_model->view_users(array('nationality'=>'AMERICAN'));
}
Model:
public function view_users($param = null) //no value passed
{
$condition = '1';
if (!empty($param)) { //Having this will trap if you input an array or not
foreach ($param as $key=>$val) {
$condition .= " AND {$key}='{$val}'"; //Use double quote so the data $key and $val will be read.
}
}
$sql = "SELECT * FROM users WHERE {$condition}"; //Use double quote so the data $condition will be read.
// Final out is this "SELECT * FROM users WHERE 1 AND nationality='AMERICAN'";
return $this->db->query($sql)->result();
}
Hello please refer my following code which is in model
public function common_report($where) {
$this->db->select('*');
$this->db->from('collect_data_form_history_db as ch');
$this->db->join('board_artwork_history_db as bh','bh.shop_id = ch.shop_id');
$this->db->where('bh.shop_id', $where);
// $this->db->where('bh.shop_id',$where);
$query = $this->db->get();
return $query->result_array();
}
what i want is all data from both table collect_data_form_history_db and board_artwork_history_db.
I get the data but in the wrong format.
In table 'collect_data_form_history_db ' i have 11 entries and in board_artwork_history_db i have 18 entries.
so data I get should be 29 rows but I get 198 rows means 11 * 18.
please tell me the solution
You need to use left join for that. Try this way
$this->db->join('board_artwork_history_db as bh','bh.shop_id = ch.shop_id', 'left');
$this->db->select('t1.*, t2.*')
->from('collect_data_form_history_db t1, board_artwork_history_db t2')
->where('t1.shop_id = t2.shop_id')
->where('t2.shop_id', $where);
$query = $this->db->get();
Try full outer join
public function common_report($where) {
$this->db->select('*');
$this->db->from('collect_data_form_history_db as ch');
$this->db->join('board_artwork_history_db as bh','bh.shop_id = ch.shop_id', 'full outer');
$this->db->where('bh.shop_id', $where);
// $this->db->where('bh.shop_id',$where);
$query = $this->db->get();
return $query->result_array();
}
I'm new to php and I've searched for the past hour and read all the documentation I could find and nothing is helping. I have a table that has a bunch of rows of data. I'm trying to pick one column from the whole table and add them all together. Here is what I got. All this tells me is how many rows there are that match my query, not the total sum of column I want. Any help is appreciated.
$res1 = $db->prepare('SELECT sum(distance) FROM trip_logs WHERE user_id = '. $user_id .' AND status = "2"');
$res1->execute();
$sum_miles = 0;
while($row1 = $res1->fetch(PDO::FETCH_ASSOC)) {
$sum_miles += $row1['distance'];
}
echo $sum_miles;
You're only returning one row in this instance. Modify your summed column to have an alias:
SELECT SUM(distance) AS totDistance FROM trip_logs ....
Now you can can fetch the row -
$row = $res1->fetch(PDO::FETCH_ASSOC);
echo $row['totDistance'];
No need to loop.
You can use SUM() without explicitely grouping your rows because if you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.
If however you want to use the SUM() function for something slightly more complicated you have to group your rows so that the sum can operate on what you want.
If you want to get multiple sums in a single statement, for example to get the distance for all users at once, you need to group the rows explicitely:
$res1 = $db->prepare("
SELECT
SUM(distance) AS distance,
user_id
FROM trip_logs WHERE status = '2'
GROUP BY user_id
");
$res1->execute();
while ($row = $res1->fetch(PDO::FETCH_ASSOC))
{
echo "user $row[user_id] has runned $row[distance] km.\n";
}
This will return the sum of distances by user, not for all users at once.
Try this if you are using a Class :
class Sample_class{
private $db;
public function __construct($database) {
$this->db = $database;
}
public function GetDistant($user_id,$status) {
$query = $this->db->prepare("SELECT sum(distance) FROM trip_logs WHERE user_id =? AND status =?");
$query->bindValue(1, $user_id);
$query->bindValue(2, $status);
try{ $query->execute();
$rows = $query->fetch();
return $rows[0];
} catch (PDOException $e){die($e->getMessage());}
}
}
$dist = new Sample_class($db);
$user_id = 10;
$status = 2;
echo $dist->GetDistant($user_id,$status);
3 framework and want to do simple sql. I have function like this but the problem is that I outputs
"SELECT listings.* FROM listings WHERE listings_id = '1' LIMIT '1'" I do not want the first listings just after select I want all the cols.
static $tableName = 'listings';
public function getListingsById($id){
$select = new Select();
$select->from(self::$tableName);
$where = new Where();
$where->equalTo('listings_id', $id);
$select->where($where);
$select->limit(1);
echo $select->getSqlString($this->getAdapter()->getPlatform());
return $this->selectWith($select);
}
SELECT listings.* FROM listings is the same as SELECT * FROM listings - both will give you all the columns from that table.