SUM two SQL rows with CodeIgniter in EE - php

I'm working at summing two different rows and their field values (forum_total_topics and forum_total_posts) from a MySQL database in ExpressionEngine using the Active Record Class provided. I have tried multiple versions of code to sum the numbers. I have attempted and failed at passing a MySQL query to the request by saying.
$SQL = "SELECT forum_id, sum(forum_total_topics) + sum(forum_total_posts)
FROM exp_forums"
ee()->db->select($SQL);
$query = ee->db->get('exp_forums');
echo $query;
to echo the total sum, and getting the following error:
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 '' at line 2
SELECT (SELECT SUM(forum_total_topics) + SUM(forum_total_posts) FROM (exp_forums)
A messy solution
So I've tried splitting the entire request up to find a solution.
I finally got the follow piece of code working by returning multiple arrays and summing those, but it looks quite messy. How, can I return and sum the two rows from the table in one line or so?
$topics = ee()->db->select_sum('forum_total_topics')->get('exp_forums');
foreach($topics->result_array() as $topicrow) {
$totalTopics = $topicrow['forum_total_topics'];
}
$posts = ee()->db->select_sum('forum_total_posts')->get('exp_forums');
foreach($posts->result_array() as $postrow) {
$totalPosts = $postrow['forum_total_posts'];
}
$total = $totalTopics + $totalPosts;
Any suggestions would be greatly appreciated!
Tried suggestions
I attempted suggestions like so,
$SQL = "SELECT forum_id, SUM(forum_total_topics + forum_total_posts) AS total
FROM exp_forums
GROUP BY forum_id";
$query = ee()->db->select($SQL);
echo $query;
With this error instead.
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_driver could not be converted to string
Filename: libraries/Functions.php(679) : eval()'d code
Line Number: 98

Try it like this instead
SELECT forum_id, sum(forum_total_topics+forum_total_posts)
FROM exp_forums
GROUP BY forum_id
sqlfiddle demo

The first thing that you tried does not work due to a small syntax error I believe...
It should be:
$SQL = "forum_id, sum(forum_total_topics) + sum(forum_total_posts) FROM exp_forums"
The initial SELECT is being added in your class function so it should not appear in your $SQL:
ee()->db->select($SQL);
That's why your error starts:
SELECT (SELECT
This is also the case with the code under "Tried Suggestions".

Try this
SELECT forum_id, SUM(forum_total_topics + forum_total_posts) AS total
FROM exp_forums
GROUP BY forum_id

Related

Codeigniter where condition is blank in $this->query()

I am facing very weird condition right now. I wrote a query in CodeIgniter with a WHERE condition like this:
$queryps = $this->db->query("SELECT count(workorderno) as total from crm_workorder where workorderno =".$sitecode."");
But I am getting this error:
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 '' at line 1
SELECT count(workorderno) as total from crm_workorder where
workorderno =
Now the weird thing is this the variable $sitecode is not blank. When I echo the query, it shows this:
SELECT count(workorderno) as total from crm_workorder where workorderno =2
But in SQL query, I am getting above error. There is nothing in WHERE condition.
I tried every possible way to find out the reason behind it but I am not able to figure out this. Thanks.
This is what you need, this must be in your model.
<?php
$this->db->select("SELECT count(workorderno) as total");
$this->db->from("crm_workorder");
$this->db->where("workorderno",$sitecode);
$queryps = $this->db->get();
?>
try this
$this->db->select('count(workorderno) as total');
$this->db->from("crm_workorder");
$this->db->where("workorderno",$sitecode);
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$row = $query->row_array();
print_r($row);
}
$queryps = $this->db->query("SELECT COUNT(workorderno) AS total FROM crm_workorder WHERE workorderno=$sitecode");
And make sure that $sitecode has a value.
TESTED
ok try this code. your error will be solve.
$queryps = $this->db->query("SELECT count(workorderno) as total from crm_workorder where workorderno ='$sitecode'");

MySQL Count does not fill variable

Problem is:
I want to count the number in my column r_start where the r_start dates are between my other two variables. But it always gives me the Error Notice: Undefined variable: z in [path] on line 173. So it doesn't fill the variable, what makes me think that the COUNT does not work porperly. I did a lot of reasearch and tried some things, but I simply don't find the cause..
$sqld = "SELECT r_start, COUNT (*) FROM reservation WHERE r_start BETWEEN '".$cid."' and '".$cod."' GROUP BY r_start";
if ($result = $con->query($sqld)) {
$z = mysqli_fetch_assoc($result);
}
This error only appears with the COUNT tag. In my other queries it works absolutly fine.
f.e.:
$sqlc = "SELECT * FROM reservation where r_ende between '".$cid."' and '".$cod."'";
if ($result = $con->query($sqlc)) {
$y = mysqli_fetch_assoc($result);
}
Can anybody tell my why? Have I done something wrong?
MySQL generally does not recognize a space between a function and the opening paren. I would also advise that you give the column an alias:
SELECT r_start, COUNT(*) as cnt
FROM reservation r
WHERE r_start BETWEEN '".$cid."' and '".$cod."'
GROUP BY r_start;
You should also learn to use parameters to pass values into queries. Not using parameters makes the code subject to unexpected (and hard-to-debug) syntax errors, as well as making it vulnerable to SQL injection.

Error in my query getting the maximum value of a varchar

i am using Codeigniter framework, and i dont know why i got error in my query. When i tried it in query builder navicat, my query runs successfully and returns the maximum number of my field varchar. But when i tried it in my model, it gives me error of :
A Database Error Occurred
Error Number: 1064You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for
the right syntax to use near '0' at line 1
Here is my query in model :
public function checkupID() {
$query = $this->db->query(' SELECT tbl_check_up.check_up_id FROM tbl_check_up ORDER BY substring_index(tbl_check_up.check_up_id, '-', 1) + 0,
substring_index(tbl_check_up.check_up_id, '-', -1) + 0 DESC LIMIT 1 ');
return $query->result();
}
Perhaps you are looking for the length of the first substring (prior to a dash) as the way to order?
SELECT tbl_check_up.check_up_id
FROM tbl_check_up
ORDER BY
length(substring_index(tbl_check_up.check_up_id, '-', 1))
LIMIT 1
;
However I am not sure what was intended for the second part of the order by.
+EDIT, correction.
-1 is valid as third parameter to substring_index

Pagination only showing first page of products; after page 1, getting "Warning: mysqli_query(): Empty query" error

When I click on the next link or any page after page 1, I get the following error:
Warning: mysqli_query() [function.mysqli-query]: Empty query
I am currently trying to view the products by group_id, here is my query:
if (isset($_GET['grpid']) && is_numeric($_GET['grpid']) ) {
$grpid = (int) $_GET['grpid'];
if ($grpid > 0) { // Overwrite the query:
$q = "SELECT company.co_id, co_name, category.cat_id, cat_name, prod_name, prod_desc, prod_tag, prod_id, prod_img FROM company, product, category WHERE company.co_id = product.co_id AND category.cat_id = product.cat_id AND product.group_id = $grpid ORDER BY company.co_name ASC, product.prod_name ASC";
}
}
I think it may be something to do with this, because if I add in the group table to the query, by adding group.group_id, group_name after the SELECT clause and group.group_id = product_group_id after the WHERE clause, I get the following error:
Error: 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 'group WHERE
I hope I have given enough information, my database is 4 tables:
product
prod_id
co_id
cat_id
grp_id
prod_name
prod_tag
prod_desc
prod_img
company
co_id
co_name
co_img
grp
grp_id
grp_name
category
cat_id
cat_name
Update
OK my query is exactly this:
if (isset($_GET['grpid']) && is_numeric($_GET['grpid']) ) {
$grpid = (int) $_GET['grpid'];
if ($grpid > 0) { // Overwrite the query:
$q = "SELECT company.co_id, co_name, grp.grp_id, grp_name, category.cat_id, cat_name, prod_name, prod_desc, prod_tag, prod_id, prod_img FROM company, product, category, grp WHERE company.co_id = product.co_id AND category.cat_id = product.cat_id AND product.grp_id = $grpid ORDER BY company.co_name ASC, product.prod_name ASC LIMIT $start, $display";
}
}
which is then immediately followed by:
$r = mysqli_query($dbc,$q) or die("Error: ".mysqli_error($dbc));
Which is the line the error points to:
Warning: mysqli_query() [function.mysqli-query]: Empty query in
I am afraid I do not know how to print out the sql and feed it directly back in?
If I don't use pagination then all of the intended products do show; the problem occurs when I am on any page other than the first page.
UPDATE 2
If I set the query to run by commenting out the if tags surrounding it, the error message changes to this:
Error: 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 'ORDER BY company.co_name ASC, product.prod_name ASC LIMIT 5, 5' at line 1
Does this shed any more light on the subject?
UPDATE 3 - solved!
Simple simple problem in the end, many thanks to BugFinder and the others who got my brain thinking about the issue properly.
The problem was that I wasn't passing the variable through to the corresponding pages when creating the url, it read:
echo 'Next';
But by adding "grpid=1" to make it read:
echo 'Next';
It has solved all of my problems!
THANK YOU GUYS, it is hard for a designer to think about programming the way programmers do, you have literally saved me days and days, great stuff!
group is a reserved word which is why it would complain. try referencing it as group with the quotes.
Try this:
$q = "SELECT c.co_id, c.co_name, cat.cat_id, cat.cat_name, p.prod_name, p.prod_desc, p.prod_tag, p.prod_id, p.prod_img FROM company AS c, product AS p, category AS cat WHERE c.co_id = p.co_id AND cat.cat_id = p.cat_id AND p.group_id = $grpid ORDER BY c.co_name ASC, p.prod_name ASC";
The reason your are getting Warning: mysqli_query() [function.mysqli-query] error is because the query is in if block and mysql_query() is outside.
Therefore I am guessing mysql_query() is called whether $q is defined or not. So when it is not defined you are getting Warning: mysqli_query() [function.mysqli-query]:

Codeigniter active record sql error

I am using the get_where() function in codeigniter, and I am getting mysql errors, dependent on what I set the limit and offset too, for example this code,
$this->db->get_where('em_user', $whereArr, 30, 0)->num_rows()
returns a mysql error that looks like this,
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 'WHERE
email = 'your#emailaddress.com' AND
password = 'letmein' LIMIT 1' at
line 2
SELECT * WHERE email =
'your#emailaddress.com' AND
password = 'letmein' LIMIT 1
However if I run this code,
$this->db->get_where('em_user', $whereArr, 30, 30)->num_rows()
it seems to run fine, it seems to run fine, it returns no results but I don not get the error(I assume the no results is because there is an offset of 30 and I only have 2 records in my table).
The sql that this code produces looks like this,
SELECT * FROM (`em_user`) WHERE `email` = 'your#emailaddress.com' AND `password` = 'letmein' LIMIT 30, 30
I dont understand how having a limit of 1 at the end of query can cause so much grief, can anyone enlighten me please?
The line
SELECT * WHERE email = 'your#emailaddress.com' AND password = 'letmein' LIMIT 1
has no FROM clause. I assume it should be:
SELECT * from em_user WHERE email = 'your#emailaddress.com' AND password = 'letmein' LIMIT 1
$this->db->get_where('em_user', $whereArr, 30, 30)->num_rows() won't get any results. num_rows() would give the you the number of results.
I think this error not related to your line of code
$this->db->get_where('em_user', $whereArr, 30, 0)->num_rows()
because in the error message it's appear LIMIT 1 but in your code you limit 30
anyway you can try this line instead of get_where
$this->db->where($whereArr)->limit(30,0)->get('em_user');
and note this line will return num rows not records
Also you can view the query to be sure if it's right or not by add this line after your get_where or query
die($this->db->last_query());
$this->db->select('*');
$this->db->from('em_user');
$this->db->where('email',$email);
$this->db->where('password',$password);
$this->db->limit('30');
$query=$this->db->get();
$result=$query->result();

Categories