CodeIgniter - MySQL join when there are no rows in secound table - mysql

I have this query in model:
public function Games() {
$q = $this->db->select('games.id, games.title, games.slug, games.dev_id, games.dev, games.plat_id, games.plat');
$q = $this->db->from('games');
$q = $this->db->join('rates', 'games.id = rates.game_id');
$q = $this->db->select_avg('rates.rate');
$q = $this->db->get();
return $q->result();
}
My goal is listing everything from games, additionally getting average rate from rates when available. Now it only shows those rows which are in both tables. How can I solve this?

Use this instruction
$this->db->select('games.id, games.title, games.slug, games.dev_id, games.dev, games.plat_id, games.plat');
$this->db->select_avg('rates.rate');
$this->db->from('games');
$this->db->join('rates', 'games.id = rates.game_id','left');
$this->db->group_by('rates.game_id');
$q = $this->db->get();
Left join will bring multiple results. using avg and group by will restrict to fetch only one row against each record.

Related

Query builder - codeigniter

I have problems building a query that uses three tables.
If I write the query as:
$query = "select domains.ID, domains.Name, domains.IP,
database_info.DB_Name, database_info.DB_User, database_info.DB_Pass,
ftp.FTP_User, ftp.FTP_Pass from domains
left join database_info on domains.ID = database_info.Domain_ID
left join ftp on domains.ID = ftp.Domain_ID
where domains.ID = $ID";
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result();
}
I get error Number 1096 No tables used SELECT *
However is I write the query using the query builder:
$this->db->select('domains.ID','domains.Name','domains.IP',
'database_info.DB_Name','database_info.DB_User',
'database_info.DB_Pass','ftp.FTP_User','ftp.FTP_Pass');
$this->db->from('domains');
$this->db->join('database_info','domains.ID =
database_info.Domain_ID', 'left');
$this->db->join('ftp','domains.ID = ftp.Domain_ID','left');
$this->db->where('domains.ID',$ID);
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result();
}
The query runs but only returns the domains.ID
Open to ideas and suggests
try this
$query = $this->db
->select('domains.ID,domains.Name,domains.IP, database_info.DB_Name,database_info.DB_User,database_info.DB_Pass,ftp.FTP_User,ftp.FTP_Pass')
->from('domains')
->join('database_info','domains.ID = database_info.Domain_ID', 'left')
->join('ftp','domains.ID = ftp.Domain_ID','left')
->where('domains.ID',$ID)
->get();
if($query->num_rows()>0)
{
return $query->result();
}
The point is in your select statement - the Query Builder only accepts one argument for your entire select statement not that many as you did
and please for the sake of security - never ever try to execute sql
statements without escaping them - CI's query builder will do this per
default - but your first example is pretty dangerous and widely open
to sql injections
Use db->query
$sql = "select domains.ID, domains.Name, domains.IP,
database_info.DB_Name, database_info.DB_User, database_info.DB_Pass,
ftp.FTP_User, ftp.FTP_Pass from domains
left join database_info on domains.ID = database_info.Domain_ID
left join ftp on domains.ID = ftp.Domain_ID
where domains.ID = $ID";
$query = $this->db->query($sql);
$result = $query->result_array();
Follow the CodeIgniter User Guide

codeigniter join 3 tables and get data from 1st table where 1st table is linked with 2nd table and 2nd table is linked with 3rd table

user_table(user_id, user_name)
user_group_table(user_id, group_id)
group_table(group_id, group_name)
I need to retrieve data (user_id, user_name, group_name)
How can I join these tables in CodeIgniter?
$this->db->query('SELECT user_table.user_id, user_table.user_name,
group_table.group_name
FROM
user_table
join user_group_table on user_group_table.user_id=user_table.user_id
join group_table on group_table.group_id=user_group_table.group_id')
->result_array();
return it and print/use the array however you like OR you can use Codeigniter Query Builder Class
$where = array(); //if u want to use any condition
$this->db->select('user_table.user_id, user_table.user_name, group_table.group_name');
$this->db->join('user_group_table', 'user_group_table.user_id = user_table.user_id');
$this->db->join('group_table', 'group_table.group_id = user_group_table.group_id');
$result = $this->db->order_by('user_table.user_id', 'desc')->get_where('property', $where)->result_array();
return $result
$this->db->select('user_table.user_id,user_table.user_name,group_table.group_name');
$this->db->from('user_group_table');
$this->db->join('user_table', 'user_table.user_id = user_group_table.user_id');
$this->db->join('group_table', 'group_table.group_id = user_group_table.group_id');
$query = $this->db->get();
$res = $query->result();
return $res;

Mysql PDO (Getting total from all colums) [duplicate]

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);

Zend 2 sql query issue

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.

Zend_Db: How to get the number of rows from a table?

I want to find out how many rows are in a table. The database that I am using is a MySQL database. I already have a Db_Table class that I am using for calls like fetchAll(). But I don't need any information from the table, just the row count. How can I get a count of all the rows in the table without calling fetchAll()?
$count = $db->fetchOne( 'SELECT COUNT(*) AS count FROM yourTable' );
Counting rows with fetchAll considered harmful.
Here's how to do it the Zend_Db_Select way:
$habits_table = new Habits(); /* #var $habits_table Zend_Db_Table_Abstract */
$select = $habits_table->select();
$select->from($habits_table->info(Habits::NAME), 'count(*) as COUNT');
$result = $habits_table->fetchRow($select);
print_r($result['COUNT']);die;
Proper Zend-Way is to use Zend_Db_Select like this:
$sql = $table->select()->columns(array('name', 'email', 'status'))->where('status = 1')->order('name');
$data = $table->fetchAll($sql);
$sql->reset('columns')->columns(new Zend_Db_Expr('COUNT(*)'));
$count = $table->getAdapter()->fetchOne($sql);
This is how it's done in Zend_Paginator. Other option is to add SQL_CALC_FOUND_ROWS before your column list and then get the number of found rows with this query:
$count = $this->getAdapter()->fetchOne('SELECT FOUND_ROWS()');
You could do a
SELECT COUNT(*)
FROM your_table
$dbo->setFetchMode( Zend_Db::FETCH_OBJ );
$sql = 'SELECT COUNT(*) AS count FROM #table';
$res = $dbo->fetchAll( $sql );
// $res[0]->count contains the number of rows
I'm kind of a minimalist:
public function count()
{
$rows = $db->select()->from($db, 'count(*) as amt')->query()->fetchAll();
return($rows[0]['amt']);
}
Can be used generically on all tables.
Add count capability to your Zend_DB Object To count all table rows
public function count()
{
return (int) $this->_table->getAdapter()->fetchOne(
$this->_table->select()->from($this->_table, 'COUNT(id)')
);
}