Error in my query getting the maximum value of a varchar - php

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

Related

Compare two Timestamps Codeigniter

I am trying to count the amount of notifications a user has got in Codeigniter. I am comparing the timestamp that is saved in each users row that records when they last checked the notifications page and the time added for each notification. However I am getting a database error:
A Database Error Occurred
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 '10:17:00' at line 5
SELECT * FROM (`notifications`) WHERE `user_id` = '1' AND `instigator_id` != '1' AND added <= 2014-11-04 10:17:00
Filename: /Users/true/Documents/Site/models/private/notifications_model.php
Line Number: 152
The Notifications controller looks like this
$data["user"] = $CI->Profile_model->get_public_profile_id($logged_user);
$count = $CI->notifications_model->get_notifications_count($data["user"][0]["notes_check"]);
The model:
public function get_notifications_count($time){
$this->db->from($this->notifications_table);
$this->db->where('user_id', $this->session->userdata("id", 0));
$this->db->where('instigator_id !=', $this->session->userdata("id", 0));
$this->db->where('added <= '.$time, '', false);
$query = $this->db->get();
$results = $query->result_array();
return count($results);
}
Your date/time values are strings. Since you don't have '-quotes around them, MySQL is seeing this:
added <= 2014-11-04 10:17:00
^^^^^^^^^^---mathematical subtraction = 1999
^^^^^^^^^--illegal unknown field/table name
It should be
added <= '2014-11-04 10:17:00'
Note the quotes.

How to get all alphabetic letters in codeigniter from DB? PHP, MySQL, CodeIgniter

I'm using this to get all letters to create alphabetic list:
SELECT DISTINCT SUBSTRING(title, 1, 1) AS letter FROM games ORDER BY letter asc
Everything OK. But then I try to pass it to codeigniter, it fails (tryed) several variants:
$this->db->distinct();
$this->db->select("SUBSTRING(title,1,1) AS letter");
$this->db->order_by("letter", "asc");
$query = $this->db->get('games');
also this one:
$this->db->query("SELECT DISTINCT SUBSTRING(title,1,1) AS letter ORDER BY letter");
$query = $this->db->get('games');
All the time I'm getting:
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 'AS letter FROM (`games`) ORDER BY `letter` asc' at line 1
SELECT DISTINCT SUBSTRING(title, `1`, `1)` AS letter FROM (`games`) ORDER BY `letter` asc
Filename: E:\wamp\www\gamecenter\system\database\DB_driver.php
Line Number: 330
What can I try to resolve this?
Pass a second parameter to the select with FALSE
$this->db->select("SUBSTRING(title,1,1) AS letter", FALSE); //This way it will not put the ` characters.
$result = $this->db->query('SELECT DISTINCT SUBSTRING(title,1,1) AS letter FROM (games) ORDER BY letter asc')->result();
I think its help you.

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.

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