I am new to Codeigniter 4 and trying to write SELECT UNION SQL Statements. According to the user guide in codeigniter 4, there is a second parameter in select() method that allows to write custom SQL Statements by setting it to false. Unfortunately it is not working. Can someone help please? Is there any alternate solution?
$query = "SELECT acnt_id, acnt_opbal as sum_amount
FROM accounts
WHERE acnt_id = '" . $acnt_id . "'
UNION
SELECT txn_acnt_id_dr as acnt_id, SUM(txn_amount_dr) as sum_amount
FROM transactions
WHERE txn_acnt_id_dr = '" . $acnt_id . "'
AND txn_date < '" . $fdate . "'
GROUP BY txn_acnt_id_dr
UNION
SELECT txn_acnt_id_cr as acnt_id, -SUM(txn_amount_cr) as sum_amount
FROM transactions
WHERE txn_acnt_id_cr = '" . $acnt_id . "'
AND txn_date < '" . $fdate . "'
GROUP BY txn_acnt_id_cr";
$result = $this->builder()->select($query, false)->get()->getResult();
According to CodeIgniter 4 Documentation ->getResult() should be used after building the query in order to produce your query
<?php
$builder = $db->table('mytable');
$query = $builder->get(); // Produces: SELECT * FROM mytable
foreach ($query->getResult() as $row) {
echo $row->title;
}
Addapting this to your code you'll get:
<?php
$builder = $this->builder()->select($query, false);
$query = $builder->get();
$result = $query->getResult();
Or make it all 1 line you can use Covariance and Contravariance:
$result = ($this->builder()->select($query, false)->get())->getResult();
Related
I have set up a query as such:
$query = 'SELECT SGC.sys_id, TBL.semester, SGC.bonus, SGC.exam, SGC.ca FROM SubjectGradeComponent AS SGC, ';
$query .= '(SELECT `sys_id`, `semester` FROM AcademicYearTerm AS AYT, SubjectYearTermLevel AS SYTL WHERE academic_year = "' . $academic_year . '" AND SYTL.subject_id = ' . $subject_id . ' AND SYTL.form_level = ' . $form_level. ' AND SYTL.yearTerm_id = AYT.yearTerm_id) AS TBL ';
$query .= 'WHERE SGC.sys_id = TBL.sys_id;';
However when I run the query, $mysql->query($query);it returns an empty result with 0 rows. Running the same query on phpmyadmin shows the desired result. I have looked around but do not understand the problem.
$mysql->error does not show any error message either
EDIT:
generated query is like this:
SELECT SGC.sys_id, TBL.semester, SGC.bonus, SGC.exam, SGC.ca FROM SubjectGradeComponent AS SGC, (SELECT `sys_id`, `semester` FROM AcademicYearTerm AS AYT, SubjectYearTermLevel AS SYTL WHERE academic_year = "2018-2019" AND SYTL.subject_id = 1 AND SYTL.form_level = 1 AND SYTL.yearTerm_id = AYT.yearTerm_id) AS TBL WHERE SGC.sys_id = TBL.sys_id;""
Question is where are the "" from?
Looks like you want a JOIN query instead.
You should also use prepared statement with placeholders ? instead of injecting values directly into the query.
$query = "SELECT SGC.sys_id,
AYT.semester,
SGC.bonus,
SGC.exam,
SGC.ca
FROM SubjectGradeComponent AS SGC
JOIN AcademicYearTerm AS AYT
ON SGC.sys_id = AYT.sys_id
JOIN SubjectYearTermLevel AS SYTL
ON SYTL.yearTerm_id = AYT.yearTerm_id
WHERE academic_year = ?
AND SYTL.subject_id = ?
AND SYTL.form_level = ?";
I am using codeigniter to build an app and I am really far in the code.
I have a table with column headers id, page, user and like. Now the problem is, in the mysql query, I realised I cant use the word like for the column name as its a sql keyword I belive.
I can't change the column name from like to something else because it would mean changing 100s of lines of php code.
Is there something that i can do to overcome the clash of the world like?
here is what I mean
$like_variable = 100;
$query = $this->db->query("SELECT * FROM `table_name`
WHERE id ='" . $qry . "' AND
page = '" . $_SESSION['p_id'] . "' AND
user_id = '" . $_SESSION['user_id'] . "' AND
like = '" . $like_variable . "'
");
// i think i cant use the world like above but I cant change the column header
Any solutions would be much appreciated thanks in advance
In SQL, you can use keywords as column names. Wrap them in ``.
SELECT * from `table_name` WHERE `like` = 100
Change like to:
`like`
Result:
$like_variable = 100;
$query = $this->db->query("SELECT * FROM `table_name`
WHERE id ='" . $qry . "' AND
page = '" . $_SESSION['p_id'] . "' AND
user_id = '" . $_SESSION['user_id'] . "' AND
`like` = '" . $like_variable . "'
");
Hiii i have two diffrent tables
staff_rotas (id,staff_id, startDateTime, endDateTime, rota_minutes, status)
staff_login (id,staff_id, actual_startDateTime,actual_endDateTime,shift_minutes, status);
I want to fetch data from both table where date between e.g (21-11-2016 to 27-11-2016) and output something like this
Timesheet
I have tried following query pls check.
<?php
$staff_data = mysql_query("SELECT * FROM staff_rotas LEFT JOIN staff_login ON
(DATE(staff_rotas.startDateTime) = DATE(staff_login.actual_startDateTime))
WHERE staff_rotas.staff_id = '123' AND DATE_FORMAT(staff_rotas.startDateTime,'%Y-%m-%d')
BETWEEN '" . $date_from . "' AND '" . $date_to . "'
UNION
SELECT * FROM staff_rotas RIGHT JOIN staff_login ON (
DATE(staff_login.actual_startDateTime) = DATE(staff_rotas.startDateTime))
WHERE staff_login.staff_id = '123' AND
DATE_FORMAT(staff_login.actual_startDateTime,'%Y-%m-%d') BETWEEN '" . $date_from . "' AND '" . $date_to . "'
ORDER BY `startDateTime` DESC")
while($data = mysql_fetch_object($staff_data)){
/*html table to show data ......
...
...
*/
}
?>
I am looking for a way to get the sum of a column. The query i am using looks like this:
public function gradeRound($rating)
{
$sql = mysql_query("Select SUM(rating) AS grades FROM" . $this->_prefix . "media_set_rating WHERE set_id = set_id");
mysql_real_escape_string($rating->rating);
$row = mysql_fetch_assoc($sql);
$grades = $row['grades'];
}
I am not sure how to get this properly formatted for the controller. right now my controller has this.
i put a text box on the page and echoed $grades - this is also included in the view as so:
$this->_view->assign('grades', $grades);
so that i can use it.
I tried replacing $setId with $rating both of which are being requested at the top.
I do not get anything out of my echo. I had -1 in there earlier. i am not sure where it was getting that from. I was trying different methods and got different results.
appreciate any hints or clues as to how to do this.
thanks
Revised 2:17 EST May 27 2013
Thanks Niko. I must be getting tired!
Here is the revised query:
public function gradeRound($rating)
{
$sql = sprintf("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating
WHERE set_id = set_id");
$sum = mysql_query($sql);
$row = mysql_fetch_assoc($sum);
$grades = $row['grades'];
return $grades;
}
$grades = $setDao->gradeRound($setId);
Your SQL query looks rather odd. Depending on the type of "set_id", it is supposed to look like this:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = '". mysql_real_escape_string($rating->rating) ."'"
);
for ยด$rating->rating` being a string. For an integer, it should be:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = ". (int) $rating->rating
);
And in total (adding also a return statement):
public function gradeRound($rating)
{
// expecting "set_id" to be an integer field
$result = mysql_query("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating WHERE set_id = ". (int) $rating->rating);
$row = mysql_fetch_assoc($result);
return $row['grades'];
}
Hope this will help You !
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );
I have this query, which selects a distinct value for a column, but I need something else in that query too. I need it to fetch a different row associated with the main select.
Let me illustrate...
This is my query:
$sql = 'SELECT DISTINCT user_id FROM ' . DONATION_SECURITY_TABLE;
$result = mysql_query($sql);
$rows = mysql_fetch_assoc($result);
mysql_free_result($result);
return $rows;
As you see it returns this query returns the DISTINCT of user_id.
If I use a function like this in a double foreach loop created using the return of the query above:
public function get_donor_status($user_id)
{
global $db;
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$payment_status = $row['payment_status'];
$db->sql_freeresult($result);
return $payment_status;
}
This function would return Completed for user_id 2, but I want it to say Pending instead. How would I change my query so it returns the last value for the corresponding user_id?
If I'm not clear enough, please let me know so I can reexplain.
Just select the last row for the user:
"SELECT payment_status FROM " . DONATION_SECURITY_TABLE . " WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1"
How about this?
$sql = 'SELECT payment_status FROM ' .DONATION_SECURITY_TABLE .
" WHERE user_id = '" . (int) $user_id . "' ORDER BY donation_id DESC LIMIT 1";
You can actually get everything in one SQL statement, no need for a double loop:
SELECT
user_id, payment_status
FROM
DONATION_SECURITY_TABLE t1
WHERE
donation_id = (select max(donation_id) from DONATION_SECURITY_TABLE t2 WHERE t2.user_id = t1.user_id)
ORDER BY
user_id