Code igniter prepending db prefix in table aliases - codeigniter

I have configured code igniter to use db prefix.
At all other places it is working as expected but while creating table aliases it is prepending db prefix.
Code is as under:-
$this->db->from('table_a');
$this->db->join('table_b', 'table_a.id = table_b.a_id', 'left');
-----
$this->db->join('table_b as tablebAlias', 'table_c.id = tablebAlias.a_id', 'left');
Assuming my dbprefix is set to value 'foo'.
Final query which is getting executed is as under:-
Select * From foo_table_a left join foo_table_b on foo_table_a.id = foo_table_b.a_id
--- left join foo_table_b as tablebAlias on foo_table_c.id = foo_tablebAlias.a_id
Any help will be highly appreciable.
Thanks,
Jatin

I found out that manual queries ignore table prefix. I also found out that there is a way to add table prefix to manual queries:
In config/database.php
One can do this:
$db['default']['dbprefix'] = "feed_";
$db['default']['swap_pre'] = "{PRE}";
So that this can be done:
$sql = "SELECT * FROM {PRE}item";
$query = $this->db->query($sql);
The {PRE} becomes feed_.
But swap_pre is not config.php which leads me to think that this is CI 2.0 feature.

Related

Can not get the url parameter in PHP

I am trying to get URL parameter in SQL, but nothing happens.
Here is my URL:
http://localhost/webshop/imagegallery.php?categori=necklace
Here is my SQL query:
$sql = 'SELECT count(productid) FROM products where productcategori=".$_GET["categori"]"';
What am I doing wrong?
Have a look at this query, too:
$sql = 'select * from products join ids on products.productid=ids.productid join photos on photos.photosid=ids.photoid where products.productcategori='".$_GET["kategori"]."' && ids.photonumber=1 ORDER BY products.productid DESC $limit';
First of all, your quotation marks seem to be the problem. Try changing your query line to this:
$sql = "SELECT count(productid) FROM products where productcategori='".$_GET["categori"]."'";
Further, you should never insert variables into a SQL query like this. Never.
The reason is that like this, your system is vulnerable for SQL injections.
Instead consider using PDO. This SO question has a nice answer on how to do it correctly.
Using that answer, this is some example code regarding the last part of your question. Note that I replaced all variables in your query string by PDO placeholders.
<?php
$pdo = new PDO('mysql:dbname=mydatabase;host=127.0.0.1;charset=utf8', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM products JOIN ids ON products.productid=ids.productid JOIN photos ON photos.photosid=ids.photoid WHERE products.productcategori=:categori && ids.photonumber=1 ORDER BY products.productid DESC LIMIT :limit_min , :limit_max";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':categori', $_GET['categori']);
$stmt->bindParam(':limit_min', ($pagenum - 1) * $page_rows, PDO::PARAM_INT);
$stmt->bindParam(':limit_max', $page_rows, PDO::PARAM_INT);
$stmt->execute();
foreach($stmt as $row) {
// do something with $row
}
?>

CodeIgniter ActiveRecord join() method wrapping numbers with backticks

This is my active record code in CodeIgniter:
$this->db->...
$this->db->join('post_likes', 'post_likes.user_id="'.$this->db->escape($online_user).'" AND post_likes.post_id=post.id', 'left');
And this is how it is interpreted:
LEFT JOIN `post_likes` ON `post_likes`.`user_id`="`3"` AND post_likes.post_id=post.id
it gives the error:
`user_id`="`3"`
How to write a direct number in active record?
Update:
removing escape
to test it on your computer you dont need to have a database. Just trying this code shows the error:
$this->db->select('*')
->from('mytable')
->join('post_likes', 'post_likes.user_id="3" AND post_likes.post_id=post.id', 'left');
$query=$this->db->get('');
var_dump($this->db->last_query());
exit(0);
result:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '` AND post_likes.post_id=post.id' at line 3
SELECT * FROM (`mytable`) LEFT JOIN `post_likes` ON `post_likes`.`user_id`="`3"` AND post_likes.post_id=post.id
You SHOULD not use the double quotes in SQL query:
$this->db->join('post_likes', "post_likes.user_id = $online_user AND post_likes.post_id=post.id", 'left');
Update:
This is a bug in the current CI stable version (fixed in v3.0-DEV), CI ActiveRecord methods (which doesn't implement really ActiveRecord) are prepared for simple usages.
I fixed this issue before by hacking the core files (by adding a parameter to join method to disable _protect_identifires).
There we go:
In system/database/DB_active_rec.php line #310, add $escape as 4th parameter:
public function join($table, $cond, $type = '', $escape = TRUE)
And change $match[3] = ... to:
if ($escape === TRUE)
{
$match[3] = $this->_protect_identifiers($match[3]);
}
So, you can use join($table, $cond, $type = '', $escape = FALSE) to disable escaping.
In addition, setting _protect_identifires globally to FALSE is not in a correct direction.
the only option remains is using custom query():
$sql = "SELECT * FROM some_table WHERE id = ?"
$this->db->query($sql, array(3));
Try this
$this->db->join('post_likes', "post_likes.user_id=$the_userid AND
post_likes.post_id=post.id", 'left');
or
$this->db->join('post_likes', 'post_likes.user_id="'.$the_userid.'" AND
post_likes.post_id=post.id', 'left');
Update:
Define
$db['default']['_protect_identifiers']= FALSE;
in "application/config/database.php" at the end.
Simple solution would be to temporarily set the protect_identifiers off before join query, like so:
$this->db->_protect_identifiers = false;
After making join query you could set it back to true
Works for me in CodeIgniter version 2.1.2
try this one
$this->db->join('post_likes', 'post_likes.user_id="{$online_user}" AND post_likes.post_id=post.id', 'left');
please let me know if you face any problem.
Dont use $this->db->escape
$this->db->join('post_likes', 'post_likes.user_id="'.$online_user.'" AND post_likes.post_id=post.id', 'left');

codeigniter join not working

<?php
$this->db->select('*');
$this->db->from('venue');
$this->db->join('venue_type vt1', 'vt1.venue_type_id = venue.venue_type_id1');
$this->db->join('venue_subtype vst1', 'vst1.venue_subtype_id = venue.venue_subtype_id1');
$this->db->join('venue_type vt2', 'vt2.venue_type_id = venue.venue_type_id2');
$this->db->join('venue_subtype vst2', 'vst2.venue_subtype_id = venue.venue_subtype_id2');
$this->db->join('venue_type vt3', 'vt3.venue_type_id = venue.venue_type_id3');
$this->db->join('venue_subtype vst3', 'vst3.venue_subtype_id = venue.venue_subtype_id3');
$this->db->where('venue_id',$id);
$query = $this->db->get();
i have venue table it has more then 1 field relation b/w venue_type. When i try to give first relation
<?php
$this->db->join('venue_type vt1', 'vt1.venue_type_id = venue.venue_type_id1');
$this->db->join('venue_subtype vst1', 'vst1.venue_subtype_id = venue.venue_subtype_id1');
its working fine , but i try to access whole its not working.
Please Help me. (It may simple but i stuck)
By Saravanan.
You need to use alias for multiple joins.
SELECT st_id, table1.us_login, table2.us_login
FROM (stream)
LEFT JOIN users AS table1 ON table1.us_id = stream.st_id_user_from
LEFT JOIN users AS table2 ON table2.us_id = stream.st_id_user_to
see the link: http://codeigniter.com/forums/viewthread/151176/
There's no $this->db->from function in Codeigniter. Use instead $this->db->select('venue.*')

Doctrine query only returning one row?

I'm new to Doctrine but somewhat familiar with SQL. I have a very simple schema with Users and Challenges. Each Challenge has a "challenger id" and a "opponent id" which are foreign keys into the User table. I want to print a list of all challenges, with the output being the names from the User table. Here is my Doctrine query;
$q = Doctrine_Query::create()
->select('u1.name challenger, u2.name opponent')
->from('Challenge c')
->leftJoin('c.Challenger u1')
->leftJoin('c.Opponent u2');
The problem is that this only returns one row. I've used the getSqlQuery() command to look at the generated SQL which ends up being:
SELECT u.name AS u__0, u2.name AS u2__1 FROM challenge c
LEFT JOIN user u ON c.challenger_id = u.id
LEFT JOIN user u2 ON c.opponent_id = u2.id
When run in a 3rd party SQL client this query retrieves all of the rows as expected. Any idea how I can get all of the rows from Doctrine? I'm using $q->execute() which I understand should work for multiple rows.
Thanks.
For me it worked by chaning the hydration mode:
$result = $query->execute(array(), Doctrine_Core::HYDRATE_SCALAR);
Set result set then returns an array instead of objects.
I just ran into this issue and in my case the problem was that my query didn't select any field from the FROM table. Example:
$query = Doctrine_Query::create()
->select(
'ghl.id as id,
ghl.patbase_id as patbase_id,
ghl.publication_no as publication_no,
ghl.priority_no as priority_no
'
)
->from('GridHitListContents ghlc')
->leftJoin('ghlc.GridHitList ghl')
As you can see there is no selected field from the GridHitListContents table.
with a $query->count() I got 2000ish results, but with $query->fetchArray() only the first one.
When I added
$query = Doctrine_Query::create()
->select(
'ghlc.id,
ghl.id as id,
...
'
)
->from('GridHitListContents ghlc')
->leftJoin('ghlc.GridHitList ghl')
I got back all my results.
$query->fetchOne() work fine for me.
Use this $result = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY)

Codeigniter: Select from multiple tables

How can I select rows from two or more tables?
I'm setting default fields for a form, and I need values from two tables...
My current code reads:
$this->CI->db->select('*');
$this->CI->db->from('user_profiles');
$this->CI->db->where('user_id' , $id);
$user = $this->CI->db->get();
$user = $user->row_array();
$this->CI->validation->set_default_value($user);
The example in the User Guide should explain this:
$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id
See the whole thing under Active Record page in the User Guide.
Just add the other table to the "->from()" method. Something like:
$this->db->select('t1.field, t2.field2')
->from('table1 AS t1, table2 AS t2')
->where('t1.id = t2.table1_id')
->where('t1.user_id', $user_id);
I think the question was not so much about joins as how to display values from two different tables - the User Guide doesn't seem to explain this.
Here's my take:
$this->db->select('u.*, c.company, r.description');
$this->db->from('users u, company c, roles r');
$this->db->where('c.id = u.id_company');
$this->db->where('r.permissions = u.permissions');
$query = $this->db->get();
I think the syntax is incorrect.
You need to select one record. I have two tables, and I have an id from one table transfer by parameter, and the relation of both tables.
Try this
$this->db->select('*')
->from('student')
->where('student.roll_no',$id)
->join('student_details','student_details.roll_no = student.roll_no')
->join('course_details','course_details.roll_no = student.roll_no');
$query = $this->db->get();
return $query->row_array();
$SqlInfo="select a.name, b.data fromtable1 a, table2 b where a.id=b.a_id";
$query = $this->db->query($SqlInfo);
try this way, you can add a third table named as c and add an 'and' command to the sql command.
// Select From Table 1 All Fields, and From Table 2 one Field or more ....
$this->db->select('table1.*, table2.name');
$this->db->from('table1, table2');
$this->db->where('table2.category_id = table1.id');
$this->db->where('table2.lang_id',$id); // your where with variable
$query = $this->db->get();
return $query->result();

Resources