Codeigniter active record sql error - php

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();

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'");

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

SUM two SQL rows with CodeIgniter in EE

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

MySQL Error 1064 Using LIMIT Clause

I'm having a strange issue running a query via PDO prepared statements that I just can't spot the issue. When running the query manually it works just fine. Here is the code (simplified for conciseness):
// Query Parameters
$params = array( 1, 5 );
// Get Products
$query = "SELECT * FROM mydb.Product
WHERE ProductId >= ?
AND IsApproved = 1
AND IsPublic = 1
LIMIT ?";
// Get Database Instance
$dbh = App\App::getDatabase()->getInstance();
// Prepare Query
if( $stmt = $dbh->prepare($query) )
{
if( $stmt->execute($params) )
{
// Return Records
}
}
Removing the LIMIT ? portion from the query returns all results as expected. Instead, when attempting to use the LIMIT and it passes 5 as the value, I get 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 ''5'' at line 5
A dump of the PDOStatement object after preparation shows:
object(PDOStatement)[59]
public 'queryString' => string 'SELECT * FROM mydb.Product
WHERE ProductId >= ?
AND IsApproved = 1
AND IsPublic = 1
LIMIT ?'
I've tried putting a semicolon at the end of the query but that gives same error. Am I having cerebral flatulence and missing something obvious?
TL;DR; Why does my prepared statement fail when using the LIMIT clause with a 1064 error?
I think this could be a duplication of
PDO Mysql Syntax error 1064
The solution is to bind limit parameter forcing it to be an int instead of a string with a simple (int) cast.
just put (int) before your limit value

DELETE statement with LIMIT and ORDER BY works in PhpMyAdmin, but not with PDO

I've to tried figure this out for half a day...
I have a script that calculates against the DB to see, if any rows should be deleted.
$number = count($INSERT)-count($INDB);
The $number variable will either be
$number = 0, which means that no rows should be deleted or inserted
$number > 0, which means that we need to insert rows
$nubmer < 0, which means that we need to delete some rows
The 1. and 2. works - but the 3. is giving me an error.
if($number < 0){
$limit = abs($number);
echo "DELETE FROM pversions
WHERE fk_p_id = $pid
ORDER BY pversion_id DESC
LIMIT $limit";
$remVersions = $pdo->prepare("
DELETE FROM pversions
WHERE fk_p_id = :pid
ORDER BY pversion_id DESC
LIMIT :lmt");
$remVersions->execute(array(":pid" => $pid, ":lmt" => $limit));
$left = count($versions)-$limit;
}
The echo could be returning this:
DELETE FROM pversions WHERE fk_p_id = 1 ORDER BY pversion_id DESC LIMIT 1
But this is giving me this PDO Exception:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]:
Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax
to use near ''1'' at line 4'
If i take the exact output of the echo from above and enter it in PhpMyAdmin, there is no problem at all. It perform the task exactly like i want it.
If I delete the LIMIT :lmt the error is not showing, and it deletes all the rows.
So I'm pretty sure the error is in the "LIMIT".
Hope someone can tell me what I'm doing wrong here.

Categories