Codeigniter placeholder in select statement (select id, 0 as placeholder, ...) - php

I have query that counts ids in joined table. I need to do an union of returned table with another table in database.
The table returned from first query has 4 columns:
-group_id
-count
-name
-description
The table I want to unite with the first one has 3 columns:
-group_id
-name
-description
I run query through phpmyadmin and it worked perfectly. Query:
SELECT group_id, size, name, description
FROM(SELECT *, count(group_id) as size
FROM table1
GROUP BY group_id) as tmp
JOIN table2
ON tmp.group_id = table2.group_id
UNION
SELECT id, 0 as size, name, description
FROM table2
But when I try to make query with codeigniter, it won't work.
Error: Unknown column '0' in 'field list'
SELECT id, 0 as size, name, description
FROM table2
Here is the codeigniter code from module:
$this->db->select('group_id, size, name, description');
$this->db->from('(select *, count(group_id) as size from table1 group by group_id) as tmp');
$this->db->join('table2', 'tmp.group_id=table2.id');
$this->db->get();
$query1 = $this->db->last_query();
$this->db->select('id, 0 as size, name, description');
$this->db->from('table2');
$this->db->get();
$query2 = $this->db->last_query();
$this->db->query($query1. ' UNION ' .$query2);
$query = $this->db->get();
return $query->result_array();
To make the story short I need to know how to make placeholder with codeigniter or is there any other, better way to get the result I need?

You have to escape your select query by adding FALSE value as the second parameter of codeigniter's active record select() function.
So, it should be written like:
$this->db->select('id, 0 as size, name, description',FALSE);
When you add FALSE value to the second parameter of it, codeigniter won't keep the first parameter to be initialized by backtick character to the query.

Related

if not exist and getting proper values from databse

I am trying to insert list of items from dev.test1 table, but I am struggling with logic ...
Face following problems:
Before insert statements I would like to add "if not exists" - select content in dev.qa_postmetas
f.URL which I am getting in second query is not coming from correct row in dev.test1 - If want to select f.URL where f.title = b.title
Query:
INSERT INTO dev.qa_posts (type, categoryid, userid, created, title, content, tags)
(SELECT 'Q_QUEUED', '1', '3', NOW(), f.title, f.img, f.tagsv
FROM dev.test1 f)
LIMIT 1;
INSERT INTO dev.qa_postmetas (postid, title, content)
(select MAX(b.postid) , 'qa_q_extra',f.URL
from dev.qa_posts b
left JOIN dev.test1 as f on b.postid = f.id)
LIMIT 1 ;
Any assistance will be appreciated
To avoid emty records try IS NULL function in MySQL.
Second query you join to another one and limiting insertion to one.
You may have more results from joined query then you attemt to insert.
Debug your second join select to check what results you have.
Take out limitation to insert all records from joined queries.
Is that what you mean?

Laravel eloquent omits null values

I'm trying to do a left join using two tables, where I need to get all user id and name in first which satisfies a condition and total number of rows in the second table for each user. If a user doesn't have a row in the second table, it must be null or zero.
This is my eloquent query.
$users->where('users.access_type', '=', 'type1')->orwhere('users.access_type', '=', 'type2')
->leftJoin(DB::raw("(SELECT user_id, COUNT(*) as count FROM table2 WHERE date > '2014-09-17 16:30:04' GROUP BY user_id) temp_table"), function($leftJoin) {
$leftJoin->on('temp_table.user_id', '=', 'users.user_id');
})->select(DB::raw('users.user_id, users.name, temp_table.count as count'))->orderBy('count')->get();
which doesn't returns the user with null count value. instead it returns the user with least count. I printed the query log and copied the raw query for the above query, filled the values and executed. which works perfectly and also returns the user with null entries. No changes made to the query obtained from query log other than adding the values. Copying the raw query below.
select users.user_id, users.name, temp_table.count as count from `users` left join (SELECT user_id, COUNT(*) as count FROM table2 WHERE date > '2014-09-17 16:30:04' GROUP BY user_id) temp_table on `temp_table`.`user_id` = `users`.`user_id` where `users`.`access_type` = 'type1' or `users`.`access_type` = 'type2' order by `count` asc
I have tried changing the column name of the user_id field for both using as user. Also tries replacing null values with zero using IFNULL. But still no go. Please let me know what am I doing wrong.
In your Eloquent query, you need to replace the last function call ...->first() by ...->get() in order to retrieve all the results instead of only the first one.

MySql - if there is no record, insert multiple rows

Before asking this question, I already search a lot of entries on Google and StockOverflow. Nothing can fulfil my question.
There are two tables - group_sale_bonuses and members. I want to check is already there records with product_id "1" in the group_sale_bonuses.
If not, I want to insert all records from members table into group_sale_bonuses with product_id "1".
My overall requirement is as follow:
IF ((Select count(id) from group_sale_bonuses where product_id = 1) = 0) THEN
INSERT INTO group_sale_bonuses (member_id, product_id, quantity_counter, credit)
SELECT id, 1, 0, 0 FROM members
END IF
But this sql causes the errors.
I know there are solutions about Insert Ignore, Where Not Exists.
But these conditions checking are based on per each record. I have thousands of records in members table. I want to make condition checking just one time like in my above sql example.
By the way, I will use this Sql in Php web application.
You could just set the code in a WHERE clause instead of the IF.
INSERT INTO group_sale_bonuses(
member_id,
product_id,
quantity_counter,
credit)
SELECT
id, 1, 0, 0 FROM members
WHERE(
SELECT
count(id) FROM group_sale_bonuses
WHERE product_id = 1
) = 0;
This should do it for all product_id's
SELECT m.product_id, m.member_id FROM members AS m
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL ;
You can filter it to a specific product_id by adding to the where clause
SELECT m.product_id, m.member_id FROM members AS m
LEFT JOIN group_sale_bonuses AS gsb ON gsb.product_id = m.product_id
WHERE gsb.product_id IS NULL AND m.product_id = 1;
Take a look at this SQLfiddle: http://sqlfiddle.com/#!2/8482c/2

get table name from count query

How do you get table name from count query, I have multiple queries and I need to get table name from the query results, here is my query
$myquery = "select count(tb_id) as num_rows from table1; select count(tb1_id) from table2...";
if (myqli_multi_query($connection, $myquery){
..
$row = mysqli_fetch_assoc($result);
$num_rows = $row["num_rows"];
..
}
The query is working fine as I can get the number of rows, but I am unable to link the table name to the number of rows (result)
I have tried this, which executes without error, but unable to get the table name still
select count(tb_id) as num_rows, 'table1' as TableName from table1
You could put an identifier into your query you can refer to later.
$myquery = "select 'table1' as tablename, count(tb_id) as num_rows from table1;
select 'table2' as tablename, count(tb1_id) as num_rows from table2;"
// and so on
You can try mysqli_fetch_field
mysqli_fetch_field($result)->table;
Just add it in to the select or the column name.
Column name:
select count(tb_id) as table1_count from table1; select count(tb1_id) as table2_count from table2.
OR sep column:
(select count(tb_id) as num_rows, 'table1' as tablename from table1)
UNION
(select count(tb1_id), 'table2' from table2...)
UNION.... etc
Edited to add: you are returning sep resultsets; consider UNION above for a single resultset.

How to select a column value as a column name and group the results as a row

How do I select a column value as a column name and group the results as a row.
I have a table as such:
id articleId label value
1 1 title Example title
2 1 description This is the description
3 1 author Me
4 2 title Example of another type of article
5 2 description Short description
6 2 author Someone else
Is it possible to select all of the rows and use the label as the column name and the value as the value of that column name and then group them by the article name.
So how I would like to have it returned:
articleId title description author
1 Example title This is the.. Me
2 Example of an.. Short descr.. Someone else
I'm using this for a CMS where the user can define the fields for an article so we don't have to customize the table's. This is why i'm not making the tables as the I would like to have it returned. I am also aware that I can just as easily convert the result to this in php.
-- edit --
Can this be done without knowing what labels are added? In this example im using title, description and author. But it could very well be something totally different like title, shortDescription, availableTo, techInformation, etc.. The idea is that the article's are customizable for the user without needing to change the database and query's
I figured I'd better post as an answer, even if not what OP would like to hear. What you are asking to do is to populate a query with a variable number of columns based on the distinct values within column label, all associated with articleID. Taking your specific example, the following would be the resultant query that I would most likely go to in this instance (though the example from #Devart is equally valid)
SELECT
t.id,
t.articleId,
t1.value AS title,
t2.value AS description,
t3.value AS author
FROM `tableName` t
LEFT JOIN `tablename` t1
ON t1.article_id = t.article_id AND t1.label = 'title'
LEFT JOIN `tablename` t2
ON t2.article_id = t.article_id AND t2.label = 'description'
LEFT JOIN `tablename` t3
ON t3.article_id = t.article_id AND t3.label = 'author'
Now expanding this to account for up to n labels, we get the following query (metacode included, this query will NOT execute verbatim)
SELECT DISTINCT label FROM `tableName`;
SELECT
t.id,
t.articleId
// for (i=1;i<= number of distinct labels) {
,t[i].value AS [value[i]]
// }
FROM `tableName` t
// for (i=1;i<= number of distinct labels) {
LEFT JOIN `tablename` t[i]
ON t[i].article_id = t.article_id AND t[i].label = [value[i]]
// }
;
So what you can do is one of the following.
SELECT t.* FROM tablename t and then have PHP process it as required
SELECT DISTINCT label FROM tablename and have PHP build the second query with the many LEFT JOINs (or MAX / GROUP BY logic if preferred)
Create a Stored Procedure to do the same as #2. This would most likely be more efficient than #2 however may be less efficient overall than #1.
You can use pivote table trick -
SELECT
articleId,
MAX(IF(label = 'title', value, NULL)) AS title,
MAX(IF(label = 'description', value, NULL)) AS description,
MAX(IF(label = 'author', value, NULL)) AS author
FROM
table
GROUP BY
articleId
Try below :
select t1.articleId,t1.title,t1.description,t1.author
from tablename as t1
left join (select max(articleId) as articleId
from tablename
group by articleId ) as t2
on t1.articleId=tsm.articleId where [.....]

Categories