convert rows into column in codeigniter - php

I have some problem when converting rows into column in codeigniter, i have a sql query to convert row into column using group_concat...
this is my query
SET ##group_concat_max_len = 5000;
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(idPertanyaan = ''',
idPertanyaan,
''', jawaban, NULL)) AS ',
idPertanyaan
)
) INTO #sql
FROM kuesioner;
SET #sql = CONCAT('SELECT idmember, ', #sql, ' FROM kuesioner GROUP BY idmember');
PREPARE stmt FROM #sql;
EXECUTE stmt;
I can't turn that query into codeigniter model
please tell me create model with this query or how to convert dynamic row into column... thanks

If you create a stored procedure in your database, then within your Model you can do this:
public function yourFunction() {
$query = $this->db->query("CALL `your_stored_procedure()`");
return $query->result_array();
}

Related

how to execute complex mysql queries in laravel

I have one below mysql query that is working fine but i want to run it laravel using prepare statement.
SET #sql = NULL;
SELECT GROUP_CONCAT(CONCAT("SELECT '",colname,":' AS 'Label',GROUP_CONCAT(JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.", colname,"'))) AS 'val' FROM mytable GROUP BY Label") SEPARATOR " UNION ")
INTO #sql
FROM
(WITH RECURSIVE data AS (
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), '$[0]') AS colname, 0 AS idx FROM mytable
UNION
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), CONCAT('$[', d.idx + 1, ']'))
AS colname, d.idx + 1 AS idx FROM data AS d
WHERE d.idx < JSON_LENGTH(JSON_KEYS(attr_details)) - 1
) SELECT colname
FROM data
GROUP BY colname) V;
PREPARE stmt FROM #sql;
EXECUTE stmt;;
Now i have tried to convert in larvel like below
$PDO=DB::connection('mysql')->getPdo();
$stmt = $PDO->prepare(<<<_OUT
SET #sql = NULL;
SELECT GROUP_CONCAT(CONCAT("SELECT '",colname,"' AS 'Label',GROUP_CONCAT(JSON_UNQUOTE(JSON_EXTRACT(attr_details,'$.", colname,"'))) AS 'val' FROM product_attributes GROUP BY Label") SEPARATOR " UNION ")
INTO #sql
FROM
(WITH RECURSIVE data AS (
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), '$[0]') AS colname, 0 AS idx FROM product_attributes
UNION
SELECT attr_details,JSON_VALUE(JSON_KEYS(attr_details), CONCAT('$[', d.idx + 1, ']'))
AS colname, d.idx + 1 AS idx FROM data AS d
WHERE d.idx < JSON_LENGTH(JSON_KEYS(attr_details)) - 1
) SELECT colname
FROM data
GROUP BY colname) V;
_OUT
);
$stmt->execute();
$result = $stmt->fetchAll();
echo "<pre>"; print_r($result); die;
I am getting this error "syntax error, unexpected 'SELECT' (T_STRING), expecting ')'",
Can anyone help me what i am doing wrong
Please check your quotes at first. In the code "SELECT GROUP_CONCAT(CONCAT("SELECT PHP recognizes that as complete string "SELECT GROUP_CONCAT(CONCAT(" and something undefined SELECT ' with the next string, without concatenation.
At least for me my IDE highlights your code as incorrect. To deal with various quotes try to use that approach
$stmt = $PDO->prepare(<<<_OUT
SELECT * FROM `table` WHERE "1";
_OUT
);
Try to write the request without #sql variable, without PREPARE stm and without EXECUTE stm. I think, PDO will deal with preparing and executing by itself.
$stmt = $PDO->prepare(<<<_OUT
SELECT GROUP_CONCAT() ...
FROM data
GROUP BY colname) V;
_OUT
);
$stmt->execute();
$stmt->fetchAll();
Try to use Laravel approach: DB::select(DB::raw($sql));
SELECT GROUP_CONCAT(CONCAT("SELECT
^-- this quote must be escaped like this: \"
PHP thinks that your SQL string ends there.
Check the other quotes as well.
Edit: Other option might be to wrap the whole SQL to single quotes (') and then just escape those inside the query (by \')

How can I convert many statement mysql dinamis to laravel eloquent?

Mysql query like this :
SET #sql_dinamis = (
SELECT GROUP_CONCAT(
DISTINCT CONCAT(
'SUM( IF(id_barang=', id_barang, ',jml_bk,0) ) AS br',
id_barang
)
)
FROM barang_keluar
);
SET #SQL = CONCAT(
'SELECT month(tgl_keluar) as m, ',#sql_dinamis,'
FROM barang_keluar
WHERE month(tgl_keluar) and year(tgl_keluar)=2019
GROUP BY month(tgl_keluar)'
);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I want to convert it to Laravel Eloquent, but I'm confused. Because there exist many statement. There exist PREPARE, EXECUTE, SET, DEALLOCATE etc. You can see query above.
How can I convert it to Laravel Eloquent?
You don't need to manually prepare statements (PREPARE, EXECUTE, DEALLOCATE) in Laravel since the Query Builder calls PDO::prepare, PDO::bindValue and PDO::execute behind the scenes.
You will be responsable for escaping/sanitizing the input however.
You can achieve this query by using a few raw methods with the query builder.
After some experimentation, I found out the real sql query created by your code is something like this:
SELECT
month(tgl_keluar) as m,
SUM(IF(id_barang=1,jml_bk,0)) AS br42,
SUM(IF(id_barang=2,jml_bk,0)) AS br48,
SUM(IF(id_barang=3,jml_bk,0)) AS br13,
SUM(IF(id_barang=4,jml_bk,0)) AS br14,
.
.
.
SUM(IF(id_barang=n-1,jml_bk,0)) AS brn-1
SUM(IF(id_barang=n,jml_bk,0)) AS brn
FROM barang_keluar
WHERE month(tgl_keluar) AND year(tgl_keluar)=2019
GROUP BY month(tgl_keluar)
To translate this into the query builder, we'll need 2 queries:
/**
* Equivalent to
*
* SELECT
* id_barang
* FROM barang_keluar;
*/
$ids_barang = DB::table('barang_keluar')
->select('id_barang')
->get();
/**
* Equivalent to
*
* SELECT
* month(tgl_keluar) as m,
* FROM barang_keluar
* WHERE month(tgl_keluar) AND year(tgl_keluar)=2019
* GROUP BY `m`;
*/
// Pass year as a variable if you want. You can also hardcode it
$year = 2019;
$query = DB::table('barang_keluar')
->selectRaw('month(tgl_keluar) as m')
->whereRaw('month(tgl_keluar) and year(tgl_keluar)=?', [$year])
->groupBy('m');
Since we didn't call ->get(), we can still add to the query.
// Now, we add all the `SUM()` statements.
foreach ($ids_barang as $row) {
$query->selectRaw("sum(if(eme_id=?,eme_empresa_id,0)) as br{$row->id_barang}", [$row->id_barang]);
}
// And finally, get the query results
$results = $query->get();
You can verify this produces the query by dumping $query->>toSql().

String Value in a concat procedure [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I know my questions sounds silly , but i'm not able to run my code because of that problem , all my procedure is correct , my only one problem is that i'm not able to use syntax that contains a string which is :
SET #query = CONCAT(#query, ' WHERE i.active=T');
I tried to use + between the apostrophe and . , however in all cases not working...
here is the full procedure
CREATE PROCEDURE stocktakess()
BEGIN
DECLARE wid INT;
DECLARE wname VARCHAR(20);
DECLARE query TEXT DEFAULT '';
DECLARE finished INT DEFAULT 0;
DECLARE whouse_cursor CURSOR FOR SELECT Id, name FROM warehouse WHERE Id IN (1,2,3,5,8);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN whouse_cursor;
SET #query = 'SELECT i.code,i.code2,i.description';
get_whouse: LOOP
FETCH whouse_cursor INTO wid, wname;
IF finished = 1 THEN
LEAVE get_whouse;
END IF;
SET #query = CONCAT(#query, ', SUM(CASE WHEN m.warehouseID=', wid, ' THEN COALESCE(m.qtyin, 0) - COALESCE(m.qtyout, 0) ELSE 0 END) AS `', wname, '`');
END LOOP get_whouse;
SET #query = CONCAT(#query, ' FROM items i LEFT JOIN itemmovement m ON m.itemid = i.Id');
SET #query = CONCAT(#query, ' WHERE i.active=T');
SET #query = CONCAT(#query, ' GROUP BY i.Id');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
CREATE PROCEDURE stocktakess()
BEGIN
DECLARE wid INT;
DECLARE wname VARCHAR(20);
DECLARE query TEXT DEFAULT '';
DECLARE finished INT DEFAULT 0;
DECLARE whouse_cursor CURSOR FOR SELECT Id, name FROM warehouse WHERE Id IN (1,2,3,5,8);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN whouse_cursor;
SET #query = 'SELECT i.code,i.code2,i.description';
get_whouse: LOOP
FETCH whouse_cursor INTO wid, wname;
IF finished = 1 THEN
LEAVE get_whouse;
END IF;
SET #query = CONCAT(#query, ', SUM(CASE WHEN m.warehouseID=', wid, ' THEN COALESCE(m.qtyin, 0) - COALESCE(m.qtyout, 0) ELSE 0 END) AS `', wname, '`');
END LOOP get_whouse;
SET #query = CONCAT(#query, ' FROM items i LEFT JOIN itemmovement m ON m.itemid = i.Id');
SET #query = CONCAT(#query, ' WHERE i.active=\'T\'');
SET #query = CONCAT(#query, ' GROUP BY i.Id');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END

Convert Dynamic Column Mysql to JSON

Heiii i have some problem, i have a dynamic query / pivot table mysql, i want convert this query to json, this is my script php
$db=new mysqli($dbhost,$dbuser,$dbpass,$dbname);
$supervisor='ganda.padeardja';
//-- query
$multi="
SET #SQL = NULL;
SELECT
GROUP_CONCAT(
DISTINCT CONCAT(
'MAX(IF(salesman = ''',
salesman,
''', total_aktivitas, 0)) AS `',
salesman,
'`'
)
) INTO #SQL
FROM
v_dashboard_supervisor_activity2
WHERE
supervisor LIKE '%ganda.padeardja%';
SET #SQL = CONCAT(
'SELECT v_calendar.cdate as aktivitas,',
#SQL,
' FROM v_dashboard_supervisor_activity2 RIGHT JOIN v_calendar ON v_calendar.cdate=v_dashboard_supervisor_activity2.tgl_aktivitas WHERE cdate BETWEEN CURDATE() - INTERVAL 6 DAY AND CURDATE() GROUP BY cdate ORDER BY cdate ASC '
);
PREPARE stmt
FROM
#SQL;
EXECUTE stmt;
";
if($result=$db->multi_query($multi)) {
$i=0;
do{
$db->next_result();
if(++$i==5)$result=$db->store_result();
}while($db->more_results() && $i<5);
}
$data=array();
$i=0;
print_r($db->error_list);
while($meta=$result->fetch_field()){
$data[$i]=array();
$data[$i]['name']=$meta->name;
$data[$i++]['data']=array();
}
$result->data_seek(0);
while($datas=$result->fetch_row()){
$i=0;
foreach($datas as $d){
$data[$i++]['data'][]=$d;
}
}
echo json_encode($data);
But result are :
Array ( )
Fatal error: Call to a member function fetch_field() on a non-object
in D:\xampp\htdocs\test\index_try2.php on line 53
And the results I expected was like this :
[{"name":"aktivitas","data":`["2015-11-22","2015-11-23","2015-11-24","2015-11-25","2015-11-26","2015-11-27","2015-11-28"]},
{"name":"abdul.qodir","data":["0","11","4","6","2","6","1"]},{"name":"andrinanta.putra","data":["0","4","7","6","5","0","0"]},{"name":"ganda.sls","data":["0","0","0","0","0","0","0"]},{"name":"paulus.jatmiko","data":["0","5","5","4","5","5","0"]},{"name":"sandy.wibowo","data":["0","0","0","6","5","12","0"]}]
Can you help me where I made ​​a mistake and miss something ??

PHP seemingly getting wrong query result

So, I built this query in SQLYog, and it returned the results I was looking for. However, when I copy-pasted it into php and used mysqli to run each query / fetch the results, my results were different (namely, one field was null rather than the correct results).
Query:
SET SESSION group_concat_max_len = 1000000;
SET #sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(CASE WHEN field_number = ''',
wp.field_number,
'''
THEN ',
IF(lng.value = NULL, 'wp.value', 'lng.value'),
' ELSE NULL END) AS ',
CONCAT(fm.field_name, IF(fm.rank <> 0, fm.rank, ''))
)
)INTO #sql
FROM wp_rg_lead_detail wp
JOIN vh_rg_form_map fm
ON fm.field_number = wp.field_number
AND fm.form_id = wp.form_id
LEFT JOIN wp_rg_lead_detail_long lng
ON wp.id = lng.lead_detail_id
WHERE wp.form_id = 1;
SET #sql = CONCAT('SELECT lead_id,', #sql, ' FROM wp_rg_lead_detail wp
LEFT JOIN wp_rg_lead_detail_long lng
ON wp.id = lng.lead_detail_id
WHERE form_id = 1 GROUP BY lead_id');
PREPARE stmt FROM #sql;
EXECUTE stmt;
My results are almost exactly the same, the only difference lies in the picture field. Here are some pictures of the difference.
Silly mistake on my part: I had to add in a section to the where clause to ensure that I was getting a single lead_id (where lead_id = $n). I'm still unsure as to exactly why I was getting different responses for the same query in php and yog, but fixing my query fixed the problem.

Categories