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
Related
Good Day Folks,
I have a children_tb and I JOIN residents_tbl to it. Then, on residents_tbl I created a view named family_head.
Is it possible to use family_head on another JOIN statement to children_tbl query statement?
Current query
$query = $this->db->select('*');
$query = $this->db->from('children_tbl');
$query = $this->db->join('residents_tbl', 'residents_tbl.residentID=children_tbl.childName', 'full');
---> ***I want to add another join here for view (family_head)***
$query = $this->db->where('childName', $id);
$query = $this->db->order_by('childID', 'DESC');
$query = $this->db->get('');
I try to use
$query = $this->db->join('family_head', 'family_head.residentID=children_tbl.familyHeadID', 'full');
but I got an error message:
Table 'db_name.family_head' doesn't exist
TIA,
C.M.
This issue was already solved.
table names are just mismatched.
I have a problem with my query and I need to join two tables from different databases now my problem is how can I execute my query. I got my syntax format from here
Please visit first this link so you could understand why my SQL syntax is like this http://www.x-developer.com/php-scripts/sql-connecting-multiple-databases-in-a-single-query
Im using CodeIgniter and here is an Idea of what my query looks like: Notice the way I'm selecting my columns: DATABASE_NAME.TABLE_NAME.COLUMN_NAME
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
$SELECT = "SELECT $ACCOUNTS.BALANCES_TABLE.IDNO, $ACCOUNTS.BALANCES_TABLE.balance";
$FROM = "FROM $ACCOUNTS.BALANCES_TABLE";
$WHERE = "$ACCOUNTS.BALANCES_TABLE.IDNO IN (SELECT $ENROLLEES.ENROLLEES_TABLE.IDNO FROM $ENROLLEES.ENROLLEES_TABLE)";
$SQL = $SELECT ." ". $FROM ." ". $WHERE;
MAIN PROBLEM: How to Execute my query?
If we do like this in codeIgniter:
$ENROLLEES->query($SQL); or $ACCOUNTS->query($SQL);
How can I execute my query that Im having multiple databases? What will I provide here[database]->query($SQL); ?
$sql="Select * from my_table where 1";
$query = $this->db->query($SQL);
return $query->result_array();
If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:
$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");
Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.
I can see what #Þaw mentioned :
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.
Next you need to use them as below:
$ENROLLEES->query();
$ENROLLEES->result();
and
$ACCOUNTS->query();
$ACCOUNTS->result();
Instead of using
$this->db->query();
$this->db->result();
See this for reference:
http://ellislab.com/codeigniter/user-guide/database/connecting.html
http://www.bsourcecode.com/codeigniter/codeigniter-select-query/
$query = $this->db->query("select * from tbl_user");
OR
$query = $this->db->select("*");
$this->db->from('table_name');
$query=$this->db->get();
return $this->db->select('(CASE
enter code hereWHEN orderdetails.ProductID = 0 THEN dealmaster.deal_name
WHEN orderdetails.DealID = 0 THEN products.name
END) as product_name')
$this->db->select('id, name, price, author, category, language, ISBN, publish_date');
$this->db->from('tbl_books');
How can I do a Query like this using the Zend framework
SELECT * FROM `productos` AS `p`
LEFT JOIN (SELECT SUM(cantidad) AS transferencias FROM transferencias WHERE upc = p`.`upc` and sucursal = 10)
AS `trans` ON trans.upc = p.upc AND trans.sucursal_clave_destino = 10
Thank you in advance.
You need to try this one.
I can't try it but the way of resolve it you can use from my query
$this->getAdapter()
->select()
->from(array('p' => 'productos'))
->joinLeft(array('trans' => $this->getAdapter()
->select()
->from('transferencias', 'SUM(cantidad)')
->where('upc IN (?)', $this->getAdapter()
->select()
->from('productos', 'upc')
)->where('sucursal = ?', 10)
), 'trans.upc = p.upc')
->where('trans.sucursal_clave_destino = ?', 10)
->query()
->fetchAll();
First of all, I'm afraid it's impossible for your query to run because the syntax is wrong. The correct way to write it is:
SELECT *, SUM(trans.cantidad) as cantidad
FROM productos AS p
LEFT JOIN transferencias AS trans
ON p.upc = trans.upc
WHERE trans.sucursal_clave_destino = 10 AND trans.sucursal = 10
First approach
I assume you have created your model in this manner: http://framework.zend.com/manual/1.12/en/learning.quickstart.create-model.html
For example, in your Default_Model_ProductosMapper:
function getXXXX(){
$select = "[THE ABOVE QUERY]";
$result = $this->getDbTable()->getAdapter()->fetchAll($select);
return $result;
}
This is the most basic approach.
Second approach
By using Zend_Db functions, which is like prepare statement in database concept. Only use it to increase safety if you are passing parameters from user input (see SQL injection), otherwise it's safe to use the first approach.
Still, in your mapper:
function getXXXX(){
$query = $this->getDbTable()->getAdapter()->select();
$query->from('productos', array());
$query->joinLeft('transferencias', 'productos.upc = transferencias.upc', array('SUM(trans.cantidad) as cantidad));
$query->where("trans.sucursal_clave_destino = 10");
$query->where("trans.sucursal = 10");
// get result
$stmt = $this->getDbTable()->getAdapter()->query($query);
$result = $stmt->fetchAll();
return $result;
}
Third approach
If you are using Database ORM like Doctrine2, you can also write SQL or DQL (Doctrine Query Language) queries, which syntax is highly similar with SQL queries but absolutely NOT the same mechanism. The document is here. This document covers both approaches above for DQL and also will tell you where to put them.
After reviewing this SO, I am having some trouble using prepared statements.
I have added the following to my db connection:
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
And here are my query statements:
$query = "SELECT schedules.schedule_name, users.name, schedules.schedule_id
FROM schedules
INNER JOIN users
ON schedules.admin_id=users.user_id
WHERE schedules.schedule_name
LIKE '%:search%'
ORDER BY schedules.schedule_name";
$stmt = $db->prepare($query);
$result = $stmt->execute(array('search' => $search_string));
$search_results = $stmt->fetchAll();
As you can see in the LIKE, I am trying to replace :search when the query is executed but it does not seem to be replaced.
When you do a parameterized query, it is not simply a string replace, and you don't surround it with singlequotes:
$query = "SELECT schedules.schedule_name, users.name, schedules.schedule_id
FROM schedules
INNER JOIN users
ON schedules.admin_id=users.user_id
WHERE schedules.schedule_name
LIKE :search
ORDER BY schedules.schedule_name";
But you want to have % wildcards around the term right? Add them when you inject it:
$result = $stmt->execute(array('search' => '%' . $search_string . '%' ));
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.