Codeigniter ActiveRecord: join backticking - php

I've a simple question: how can I use CodeIgniter's ActiveRecord join function? I want this:
LEFT JOIN cimke ON (mk_terem.id_kicsoda=5 AND mk_terem.id_target=cimke.id_cimke)
LEFT JOIN tanar ON (mk_terem.id_kicsoda=1 AND mk_terem.id_target=tanar.id_tanar)
But if I use $this->db->join(cimke,"mk_terem.id_kicsoda=5 AND mk_terem.id_target=cimke.id_cimke"), the value 5 will be between backticks.
How can I do this?
UPDATE
What I want? If mk_terem.id_kicsoda is 1, then I want tanar.nev and when mk_terem.id_kicsoda is 5, I want cimke.nev.
The full SQL-query:
SELECT
terem.nev terem_nev,
elem_tipus.nev tipus_nev,
(IFNULL(cimke.nev,tanar.nev)) nev
FROM mk_terem
LEFT JOIN terem ON mk_terem.id_terem=terem.id_terem
LEFT JOIN cimke ON (mk_terem.id_kicsoda=5 AND mk_terem.id_target=cimke.id_cimke)
LEFT JOIN tanar ON (mk_terem.id_kicsoda=1 AND mk_terem.id_target=tanar.id_tanar)
LEFT JOIN elem_tipus ON (mk_terem.id_kicsoda=elem_tipus.id_kicsoda)

Only a simple workaround, ugly, not elegant, but it works in this case:
$original_reserved = $this->db->_reserved_identifiers;
$this->db->_reserved_identifiers[] = 5;
$this->db->_reserved_identifiers[] = 1;
// or any other values
$this->db->join('with critical values and conditions');
// some db-stuff
$this->db->_reserved_identifiers = $original_reserved;
If anybody knows better please show it!

$this->db->join('cimke', 'mk_terem.id_target = cimke.id_cimke');
$this->db->join('tanar', 'mk_terem.id_target = tanar.id_tanar');
$this->db->where('mk_terem.id_kicsoda', 5);
$this->db->where('mk_terem.id_kicsoda', 1);
or use
$this->db->query('AND_YOUR_RAW_SQL_QUERY_HERE');

Another simple solution would be to temporarily set the protect_identifiers off like so:
$this->db->_protect_identifiers = false;
After making the query you could set it back to true

I know i am very answering this question very late. Just i am sharing my knowledge. It may help us to known something. If I am wrong, Please tell me. I am answering this question by the full query you posted on your question. Kindly check it below.
$this->db->from('mk_terem');
$this->db->select('terem.nev terem_nev, elem_tipus.nev tipus_nev, (IFNULL(cimke.nev,tanar.nev)) nev');
$this->db->join('terem','mk_terem.id_terem=terem.id_terem','left');
$this->db->join('cimke','(mk_terem.id_kicsoda=5 AND mk_terem.id_target=cimke.id_cimke)','left');
$this->db->join('tanar','(mk_terem.id_kicsoda=1 AND mk_terem.id_target=tanar.id_tanar)','left');
$this->db->join('elem_tipus','(mk_terem.id_kicsoda=elem_tipus.id_kicsoda)','left'); $this->db->get();
I got the query which you posted in the question as full Query. Check it below.
SELECT `terem`.`nev` terem_nev, `elem_tipus`.`nev` tipus_nev, (IFNULL(cimke.nev, `tanar`.`nev))` nev FROM (`mk_terem`) LEFT JOIN `terem` ON `mk_terem`.`id_terem`=`terem`.`id_terem` LEFT JOIN `cimke` ON `mk_terem`.`id_kicsoda`=`5` AND mk_terem.id_target=cimke.id_cimke) LEFT JOIN `tanar` ON `mk_terem`.`id_kicsoda`=`1` AND mk_terem.id_target=tanar.id_tanar) LEFT JOIN `elem_tipus` ON `mk_terem`.`id_kicsoda`=`elem_tipus`.`id_kicsoda)`
I believe everything is possible to do by codeignitor Active record. No need to execute the query in $this->db->query() as raw sql.
#uzsolt: I am explaining this because of the argument you made under the topic "http://stackoverflow.com/questions/8344769/writing-sql-queries-in-codeigniter-2-0". And I will try your other bugs you posted under the above URL too shortly and get back to you. If i am anything wrong, kindly let me know. Thanks. :)

If you swap the conditions around AND, it will work! CodeIgniter only escapes the first part of the condition.
So, inthis should work:
$this->db->join('cimke',"mk_terem.id_kicsoda = 5 AND mk_terem.id_target = cimke.id_cimke", "left")

Related

Sql query in yii2

I would like to execute such a command:
SELECT number.phone_number
FROM number
LEFT JOIN ordered_number
ON ordered_number.number_id=number.id
WHERE ordered_number.order_id=123
with Yii2. I do this:
$numery = Number::find()
->select('number.phone_number')
->leftJoin('ordered_number', ['ordered_number.number_id' => 'number.id'])
->where(['ordered_number.order_id' => 123])
->createCommand()
->rawSql;
But I get then this:
'SELECT `number`.`phone_number` FROM `number` LEFT JOIN `ordered_number` ON `ordered_number`.`number_id`='number.id' WHERE `ordered_number`.`order_id`=123'
Which doesn't work. When I put the first thing right into my base, I get 4 results, which is correct. But when I do (I think exactly the same) with Yii, I have troubles, because it is null. The only differences between what I have written and what appears after rawSql, are ` and '.
Sorry, I've just read docs for this method - it should be:
->leftJoin('ordered_number', 'ordered_number.number_id = number.id')
because using the where() kind of conditions with array leads to comparing field to string.
Maybe this link could help you a lot , the comments of ActiveRecord.

Join query codeigniter with where condition returns all rows

Here is my join query for getting data from two tables.
$this->db->select('*');
$this->db->from('george_hotel_bkd_customers');
$this->db->where('george_hotel_bookings.bookingref',$ref);
$this->db->join('george_hotel_bookings', 'george_hotel_bookings.user_id = george_hotel_bkd_customers.user_id');
$query = $this->db->get();
According to my where condition it returns only one row but it will returns all the rows with matches the join condition.
Seems like my where condition is not executed here.
please help me
What does $ref =, how many results should it pick up roughly?
what do you get when you omit the where? if you get full result then must be an issue with $ref value, or, that is the result.
Just a note, you don't need to select(*), this is default, if this is an just for examples sake, sorry for picking up. You can also add the ->from(whaterver_table) to ->get(whatever_table) You need to add ->get() anyway, so why not remove the ->from() line, just a choice of readability, but i did not realise you could do this for a while, so thought id add it to my answer.
Or another problem solving path is whether the join should be 'left' as 3rd arg. IE is there always a join?
Altering the position or the join in the statement would not make any difference, as Anant suggested
$this->db->select('*');
$this->db->from('george_hotel_bkd_customers');
$this->db->join('george_hotel_bookings', 'george_hotel_bookings.user_id = george_hotel_bkd_customers.user_id');
$this->db->where('george_hotel_bookings.bookingref',$ref);
$query = $this->db->get();
always where is last

using concat in where like query

First off, I'm a beginner at this so please be patient with me. I've tried searching the forums here, and elsewhere and from what I can see I'm doing it right.. but I get an error. to "Check syntax to use near 'LIKE CONCAT(games.tag, ' Special%') AT LINE X". So clearly I'm doing it wrong.. But everything I have found says I've done it right. Someone please help I'm getting frustrated.
SELECT
games.tag,
ribbons.name,
members.username,
members.joined
FROM
member_ribbons
INNER JOIN ribbons
ON member_ribbons.ribbon_id = ribbons.id
INNER JOIN games
ON ribbons.game_id = games.id
INNER JOIN members
ON member_ribbons.member_id = members.id
WHERE games.id = members.primary_game AND discharged='000-00-00' AND ribbons.name = LIKE CONCAT(games.tag, ' Special %');
An Example
ribbons.name will contain "BF4 Special Consideration"
I need to be able to find that specific one.. but the only thing that changes is the first word which is contained in games.tag. The rest of the Query works. Just need to figure out how to get it to do this and I'm good. However Searching google everywhere and here has not shown any examples of how to do this.. Is it even possible? Clearly I'm doing this wrong.
you have extra =
change this
AND ribbons.name = LIKE CONCAT
^----//--no need this
to
AND ribbons.name LIKE CONCAT

PostgreSQL Database - Inner Join Query Error

With the help of this community, I was able to produce a query using an inner join which I thought would work for what I'm trying to do. Unfortunately, when I attempted to run the query found below, I received the following error:
ERROR: table name "bue" specified more than once
From what I've read on Google, some people have said that the "FROM bue" is not needed, but when I removed this, I got another error found below:
ERROR: syntax error at or near "INNER" at character 98
I'd very much appreciate your assistance in troubleshooting this. Thank you so very much.
Query:
UPDATE
bue
SET
rgn_no = chapterassociation.rgn_no,
chp_cd = chapterassociation.chp_cd
FROM
bue
INNER JOIN
chapterassociation
ON bue.work_state = chapterassociation.work_state
AND bue.bgu_cd = chapterassociation.bgu_cd
WHERE
bue.mbr_no IS NULL AND bue.chp_cd IS NULL
In PostgreSQL, specifying the table to be updated needs to be done only in the UPDATE clause, e.g. UPDATE bue. The FROM clause is only for additional tables referenced in the query. (If you were doing a self-join on bue, you would mention it again in the FROM clause, but you aren't in this case.)
The second error you get is likely just a simple syntax error. The other tricky thing is that JOIN/ON syntax doesn't fit in the FROM clause, so you have to move the join conditions to the WHERE clause. Try something like:
UPDATE
bue
SET
rgn_no = chapterassociation.rgn_no,
chp_cd = chapterassociation.chp_cd
FROM
chapterassociation
WHERE
bue.mbr_no IS NULL AND bue.chp_cd IS NULL
AND bue.work_state = chapterassociation.work_state
AND bue.bgu_cd = chapterassociation.bgu_cd
See http://www.postgresql.org/docs/current/interactive/sql-update.html.
(N.B. At least I don't know how to put JOIN/ON into an UPDATE statement... I could be missing something.)

CakePHP: add variables to query in controller

I have a controller action that uses a sql query:
$tag = $this->params['tag'];
$this->set('projects', $this->Project->query('SELECT * FROM projects INNER JOIN projects_tags ON projects.id = projects_tags.project_id INNER JOIN tags on projects_tags.tag_id = tags.id WHERE tags.tag LIKE $tag'));
As you can see at the end I want to use a where clause with the $tag variable but I'm not sure how the syntax would go. As I'm getting the error
Unknown column '$tag' in 'where clause'
Can someone steer me in the right direction?
Ta,
Jonesy
I would strongly advise you to use the Cake ORM instead of raw queries, especially if you're going to plug URL parameters into it. Conditions on HABTM tables can be tricky, but you can build your joins using Cake's ORM syntax as well!
Read the manual, section 3.7.6.9 Joining tables.
Should you want to use Cake's ORM, the following code should provide results equivalent to your raw SQL query:
$this->loadModel('ProjectsTag'); // Load the joining table as pseudo-model
// Define temporary belongsTo relationships between the pseudo-model and the two real models
$this->ProjectsTag->bindModel(array(
'belongsTo' => array('Project','Tag')
));
// Retrieve all the join-table records with matching Tag.tag values
$result_set = $this->ProjectsTag->find('all',array(
'conditions' => array('Tag.tag LIKE' => "%{$tag}%")
));
// Extract the associated Project records from the result-set
$projects = Set::extract('/Project', $result_set);
// Make the set of Project records available to the view
$this->set(compact('projects'));
in php there's a difference between single and double quotes... basically, single quotes dont evaluate the variables... use double quotes instead
And i think that LIKE will need also single quotes.. i'm not really sure
"SELECT * FROM projects INNER JOIN projects_tags ON projects.id = projects_tags.project_id INNER JOIN tags on projects_tags.tag_id = tags.id WHERE tags.tag LIKE '$tag'"
i know.. i know.. people will start talkin' about sql injection.. and the need to scape the caracters... that's another question =)
good luck!
I would at least consider using the cakephp sanitize functions on your tag strings if they are user sourced. See http://book.cakephp.org/view/1183/Data-Sanitization or if using mysql as the db at least consider using http://www.php.net/manual/en/function.mysql-escape-string.php or do something to filter your user input. But the best thing is to make use of the CakePHP orm stuff.
Modify your query as:
$this->set('projects',
$this->Project->query("SELECT * FROM projects
INNER JOIN projects_tags
ON projects.id = projects_tags.project_id
INNER JOIN tags ON projects_tags.tag_id = tags.id
WHERE tags.tag LIKE '" . $tag . "'") //problem was here
);
and it will work.

Categories