How to view data based on user in codeigniter - mysql

I want to view data from mysql in codeigniter based on user who is logged in
but I got an error "A Database Error Occurred". I think I wrote the wrong code
t.USER = $this->session->userdata('user_id');
Here's the code:
function get_rekomen()
{
$query = $this->db->query("SELECT
c.*,
t.produk_id,
t.id_transdet,
t.kategori_id,
t.total_qty,
t.USER
FROM
transaksi_detail AS t
LEFT JOIN
(
SELECT
g.id_produk,
p.slug_produk,
p.foto,
p.foto_type,
p.harga_diskon,
p.diskon,
p.harga_normal,
p.judul_produk,
g.kat_id,
k.judul_kategori
FROM
(
SELECT
MAX(m.id_produk) AS id_produk,
m.kat_id
FROM
produk AS m
GROUP BY
m.kat_id
)
AS g
INNER JOIN
produk AS p
ON p.id_produk = g.id_produk
LEFT JOIN
kategori AS k
ON k.id_kategori = g.kat_id
)
AS c
ON c.kat_id = t.kategori_id
WHERE
t.USER = $ this -> session -> userdata('user_id');
<<// i think here's the problem
ORDER BY
total_qty DESC limit 1")->result();
return $query;
}
and the question is what is the correct code?

Here's one solution, but first make sure on your controller the $this->load->library('session'); is loaded or you can just add in on autoload.php.
Also you must add parameter to your model that will handle the user_id in session, so for example here's your model looks like:
function get_rekomen($user_id) { ...your query here... }
Then on condition using the user_id will be
t.USER = $user_id;
So on your controller, you can call your model like:
$user_id = $this->session->userdata('user_id');
$this->ModelClass->get_rekomen($user_id);
Additional: On your login phase, if the user success from logging in, the you must set the user data on session such as this $this->session->set_userdata('user_data', $session_data);
Hope this helps!

Maybe you can use this. You need to define $user_id first before adding them to WHERE statement...
$user_id = $this->session->userdata('user_id');
$sql = "SELECT c.*, t.produk_id, t.id_transdet, t.kategori_id, t.total_qty, t.USER
FROM transaksi_detail AS t
LEFT JOIN(SELECT g.id_produk, p.slug_produk, p.foto, p.foto_type, p.harga_diskon, p.diskon, p.harga_normal, p.judul_produk, g.kat_id, k.judul_kategori
FROM(SELECT MAX(m.id_produk) AS id_produk, m.kat_id
FROM produk AS m
GROUP BY m.kat_id)
AS g
INNER JOIN produk AS p ON p.id_produk = g.id_produk
LEFT JOIN kategori AS k ON k.id_kategori = g.kat_id)
AS c ON c.kat_id = t.kategori_id
WHERE t.USER = '$user_id'
ORDER BY total_qty DESC limit 1";
$query = $this->db->query($sql);
return $query->result();
Hope this can help you...

Related

Mysql how can i sql two tables and count groupid from the second

I'm trying to make an Sql , that get all data from first table "posts_main" and then get the count of comments from second table "posts_comments"
I tried:
$sql = "SELECT * FROM posts_main, count(posts_comments.groupid)
INNER JOIN posts_comments ON posts_comments.groupid = posts_main.id
WHERE posts_main.user_id = '$user_id'
GROUP BY posts_main.id";
Please, how can i do that ?
thanks....
Try with below query.
$sql = "select posts_main.*,
(select groupid from posts_comments where groupid = posts_main.id group by groupid ) as count_group
from posts_main
WHERE posts_main.user_id = '$user_id' ";
Try this with subquery
SELECT posts.*,cnt FROM posts_main
INNER JOIN (select posts_comments.groupid,count(posts_comments.groupid) as cnt
group by posts_comments.groupid)a
ON a.groupid = posts_main.id
WHERE posts_main.user_id = '$user_id'

MySQL - alternative for like - regexp?

i have got over one milion record in my database table.
When I use like is very slowly, when i use match against they lost some records.
I create help table:
tag_list
tag_id
tag_name
tag_rel_message
tag_id
messag_id
messages
message_id
message_text
in tag_list i add all words of $message_text - explode(" ", $message_text);
My new query is:
SELECT m.*
FROM tag_rel_messages trm
INNER JOIN messages m ON (trm.message_id = m.message_id)
INNER JOIN tag_list tl ON (trm.tag_id=tl.tag_id
WHERE tl.tag_name REGEXP 'pionas' AND tl.tag_name REGEXP 'website'
GROUP By trm.message_id
But not display any records.
What's wrong with this query?
Maybe i should use something other than REGEXP?
Thanks for help
I'm not sure how one column could match two things at the same time! You can use OR in place of AND, or you can use a single call to REGEXP.
SELECT m.*
FROM tag_rel_messages trm
INNER JOIN messages m ON (trm.message_id = m.message_id)
INNER JOIN tag_list tl ON (trm.tag_id=tl.tag_id
WHERE tl.tag_name REGEXP 'pionas|website'
GROUP By trm.message_id
You need to join with the tag_list and tag_rel_message tables twice to match two different tags.
SELECT m.*
FROM messages AS m
JOIN tag_rel_messages AS trm1 ON m.message_id = trm1.message_id
JOIN tag_list AS t1 ON t1.tag_id = trm1.tag_id
JOIN tag_rel_messages AS trm2 ON m.message_id = trm2.message_id
JOIN tag_list AS t2 on t2.tag_id = trm2.tag_id
WHERE t1.tag_name = 'pionas' AND t2.tag_name = 'website'
Another way to do it is to join with either tag, and count the number of results per message
SELECT m.*
FROM messages AS m
JOIN tag_rel_messages AS trm ON m.message_id = trm.message_id
JOIN tag_list AS t ON t1.tag_id = trm.tag_id
WHERE t.tag_name IN ('pionas', 'website')
GROUP BY m.message_id
HAVING COUNT(*) = 2
This second form is a little easier to generalize to any number of tags. Put all the tags in the IN clause, and change the HAVING clause to match the number of tags.
$words = array('pionas', 'website');
$tags_id = array();
foreach ($words as $key => $val) {
$sql = "SELECT tag_id FROM tag_list WHERE tag_name LIKE '%".$val."%'";
$records = $db->query($sql);
$tags_id[$key] = array_column($records, "tag_id");
}
$inner_array = array();
foreach ($tags_id as $k => $v) {
$short_name = "trm_".$k;
$inner_array[] = " INNER JOIN tag_rel_message as ".$short_name." ON ( ".$short_name.".message_id = m.message_id AND ".$short_name.".tag_id IN (".implode(", ", $v).")) ";
}
$sql = "SELECT DISTINCT m.* FROM messages m".implode(" ", $inner_array);
I think this is the same:
SELECT * FROM messages WHERE message_text like '%pionas%' AND message_text like '%website%'

Drupal 7 DB API Query with Condition db_or etc

I'm having a little issue with getting an sql query to work in drupal 7.
Basically, I'd like to know if my drupal code for the db_api is correct for the SQL query that I expect it to generate.
Please see code below:
/*
SQL Query
Note: The the 'a' in '%a%', is just a sample of some text input by a user.
*/
SELECT u.uid, fn.field_first_name_value, ln.field_last_name_value
FROM role r
JOIN users_roles ur ON (r.rid = ur.rid)
JOIN users u ON (u.uid = ur.uid)
JOIN field_data_field_first_name fn ON (fn.entity_id = u.uid)
JOIN field_data_field_last_name ln ON (ln.entity_id = u.uid)
WHERE (fn.field_first_name_value LIKE '%a%' OR ln.field_last_name_value LIKE '%a')
AND r.name = 'custom_role'
LIMIT 0, 5
/*
DRUPAL 7 DB API CODE
*/
$name = $_POST['name'];
$res = db_select('role', 'r');
$res->join('users_roles', 'ur', 'ur.rid = r.rid');
$res->join('users', 'u', 'u.uid = ur.uid');
$res->join('field_data_field_first_name', 'fn', 'fn.entity_id = u.uid');
$res->join('field_data_field_last_name', 'ln', 'ln.entity_id = u.uid');
$res->fields('u', array('uid'));
$res->fields('fn', array('field_first_name_value'));
$res->fields('ln', array('field_last_name_value'));
$or = db_or()->condition('fn.field_first_name_value', '%'.db_like($name).'%', 'LIKE');
$or->condition('ln.field_first_name_value', '%'.db_like($name).'%', 'LIKE');
$res->condition($or)->condition('r.name', 'custom_role', '=');
$res->range(0,5);
$res->execute();
Also, if there is way that I can see the generated sql by the db api, that would be great for debugging.
Thanks.
I cannot execute it because i do not have the same tables like you but your generated query looks good.
SELECT u.uid AS uid, fn.field_first_name_value AS field_first_name_value, ln.field_last_name_value AS field_last_name_value
FROM
{role} r
INNER JOIN {users_roles} ur ON ur.rid = r.rid
INNER JOIN {users} u ON u.uid = ur.uid
INNER JOIN {field_data_field_first_name} fn ON fn.entity_id = u.uid
INNER JOIN {field_data_field_last_name} ln ON ln.entity_id = u.uid
WHERE ( (fn.field_first_name_value LIKE :db_condition_placeholder_0 ESCAPE '\\') OR (ln.field_first_name_value LIKE :db_condition_placeholder_1 ESCAPE '\\') )AND (r.name = :db_condition_placeholder_2)
LIMIT 5 OFFSET 0
If you want to print the query yourself you can use
print $res->__toString() . "\n\n";
var_export($res->getArguments());
Or
watchdog('MY_QUERY_DEBUG', $res->__toString(), $res->getArguments());
To add it to your watchdog log.

MySQL - combining multiple queries

I currently have the following queries (and some surrounding vB code). I was hoping I could slim this up into a single SELECT statement versus having to run 10 more on each page to get that names of individuals.
$results = $db->query_read_slave("
SELECT user.id AS steam, user.skills AS level
FROM wcsp.wcgousers AS user
WHERE race = '_wcs_'
ORDER BY ABS(user.skills) DESC LIMIT 10
");
$rank = 1;
while ($user = $db->fetch_array($results)) {
$result = $db->query_first("
SELECT old.name AS name
FROM wcsp.warn_oldnames AS old
WHERE id = '$user[steam]'
ORDER BY lasttime
DESC LIMIT 1
");
$listing[] = array("id" => $user['steam'], "level" => $user['level'], "name" => $result['name'], "rank" => $rank);
$rank += 1;
}
I have tried LEFT JOIN but the issue I run into is that I would need a subquery in the LEFT JOIN similar to:
SELECT user.id AS steam, user.skills AS level, names.name AS name
FROM wcsp.wcgousers AS users
LEFT JOIN
(
SELECT names.name
FROM wcsp.warn_oldnames AS names
WHERE id = wcsp.wcgousers.id
ORDER BY lasttime DESC LIMIT 1
) AS names
ON names.id = users.id
WHERE users.race = '_wcs_'
Which won't work due to the different database check inside the subquery.
If I understand you correctly, you want to get the latest Name for every users.
SELECT a.id AS steam,
a.skills AS level,
b.name
FROM wcgousers a
INNER JOIN warn_oldnames b
ON a.ID = b.ID
INNER JOIN
(
SELECT ID, MAX(lasttime) max_date
FROM warn_oldnames
GROUP BY ID
) c ON b.ID = c.ID AND
b.lastTime = c.max_date
WHERE a.race = '_wcs_'
-- ORDER BY ABS(a.skills) DESC
-- LIMIT 10

Duplicate column name 'user_id' problem

I'm having a problem trying to count the number of user records according to the user's id, however I'm using a subquery to join 2 tables that one has a count parameter but I get an error saying duplicate column name 'user_id.
The query:
$sql = "SELECT loc.location_id,
COUNT(loc.location_id) AS total_records
FROM locations loc
LEFT JOIN
(
SELECT usr.*,
loc.*
FROM
(
members usr
INNER JOIN locations loc
)
WHERE usr.user_id = " . $user_id . "
AND usr.account_disabled = 0
ORDER BY loc.submit_date DESC
) usr ON (loc.user_id = usr.user_id)";
All I need it is to return the user's info and the total_records count done by the COUNT function.
Cheers.
EDIT:
This is what I get returned for this SQL:
SELECT loc.location_id,
loc.street_name,
loc.city,
loc.state,
loc.county,
loc.country,
usr.user_id,
usr.username,
COUNT(loc.location_id) AS total_records
FROM locations loc
INNER JOIN members usr ON (loc.user_id = usr.user_id)
WHERE loc.user_id = $user_id
AND usr.account_disabled = 0
GROUP BY loc.location_id
It's not exactly clear why you've got the derived resultset or the LEFT JOIN. Try this:
SELECT loc.location_id,
COUNT(loc.location_id) AS total_records
FROM LOCATIONS_TABLE loc
INNER JOIN MEMBERS_TABLE usr
ON (loc.user_id = usr.user_id)
WHERE loc.user_id = $user_id
AND usr.account_disabled = 0
GROUP BY loc.location_id
I think the problem is this part:
SELECT usr.*,
loc.*
Both tables have a user_id