Getting extra space in Codeigniter like query - php

My code is
$this->db->like('postcoderegion','Brighton And Hove');
$query = $this->db->get('postcode');
$result = $query->result();
Mysql query
SELECT * FROM `postcode` WHERE postcoderegion LIKE '%Brighton And Hove%' ESCAPE '!'
When i see mysql query then i got an extra space between 'AND' or 'Hove'. Please let me know how can i remove this extra space. when i not set Hove then it not produced any space.

UPD: it's fixed in 3.0.2 (https://github.com/bcit-ci/CodeIgniter/issues/4093), so please update to the latest version (3.0.5 currently).
(Below is a previous answer, not relevant.)
I think it's a bug in CI's query builder, so I've submitted an isuue — https://github.com/bcit-ci/CodeIgniter/issues/4551
See here — https://github.com/bcit-ci/CodeIgniter/blob/3.0.5/system/database/DB_query_builder.php#L2378 (it's for 3.0.5, but this part of code is the same as for 3.0.1).
You can try to fix it yourself or wait till it's fixed from CI team.

Related

PostgresSQL production table database has capital letter

may I know how can I select my database if all the column has all capital letters. I run this query and it works
SELECT public.countryhomes."PH" from public.countryhomes where public.countryhomes."Read_Datetime" = '2022-09-21 10:15:00'
However when I tried to put inside my PHP code it doesn't work. I run like this
$sqlx = pg_query($dbconn, 'SELECT public.countryhomes."PH" from public.countryhomes where public.countryhomes."Read_Datetime" = '.$date.'');
When I tried to echo the sqlx, it returned with error saying syntax error near the quot and return something like this
SELECT public.countryhomes."PH" from public.countryhomes where public.countryhomes."Read_Datetime" = 2022-09-21 10:15:00
means, it didnt read my quotes near the datetime. Does anyone know how to fix this? Because I am not allowed to change the database since its in production. Please help

Why comparing Strings in MySQL query is not working

I am running a very simple SELECT query in MySQL and it's not working.
SELECT string_name FROM table_name;
This is giving me required output. Like
This is string one.
This is string two.
This is string three.
and so on...
But if I am running a query like this
SELECT * FROM table_name WHERE string_name='This is string one'
It's not giving any output. I even tried TRIM function.
SELECT * FROM table_name WHERE TRIM(string_name)=TRIM('This is string one')
But it's still not giving any output.
Please suggest what I am missing here. Is it because of some formatting or am I doing any silly mistake. By the way, Strings are saved as VARCHAR in the database.
To reiterate from comments; sometimes "non-printing" control characters (like newlines) can make their way into data they were never intended to be a part of. You can test for this by checking CHAR_LENGTH of field values versus what you actually see. Obviously, on large amounts of data this can be difficult; but if you know of one problematic value already, you can use this method to confirm this is the problem on that row before attempting to identify the offending character.
Once this problem is confirmed, you can use queries with MySql's ASC() and substring functions to identify character codes until you find the character; it can be best to start from the end of the string and work back, as often the offending characters are at the end.
The character or characters identified in known problem rows are often the cause of other problem rows as well, so identifying the issue in one known row can actually help resolve all such problems.
Once the character code(s) are identified, queries like WHERE string_name LIKE CONCAT('%', CHAR(13), CHAR(10)) should work (in this case for traditional Windows newlines) to identify other similar problem rows. Obviously, adjust character codes and wildcards according to your circumstances.
If no row should ever have those characters anywhere, you should be able to clean up the data with an update like this:
UPDATE theTable SET theString = REPLACE(REPLACE(theString, CHAR(10), ''), CHAR(13), '') to remove the offending characters. Again, use the codes you've actually observed causing the problem; and you can convert them to spaces instead if circumstances are better handled that way, such as a newline between two words.
Have you tried using LIKE for debugging purposes?
SELECT * FROM table_name WHERE string_name LIKE 'This is string one'
/!\ Don't just switch from = to LIKE, read about why here
TLDR:
= is apparently 30x faster.
Use = wherever you can and LIKE wherever you must.
First of all, I must acknowledge the points made by #Uueerdo were actually the the main cause of this issue. Even I was somewhat sure that there are some hidden characters in the string causing all the issue but I was not sure how to find and fix that offending character.
Also, the approach suggested by #Uueerdo to check and replace the offending character using the ASCII code seems quite legit but as he himself mentioned that this process will take lot's of time and one have to manually check every string for that one offending character and then replace it.
Luckily after spending couple of hours on it, I came up with a much faster approach to fix the issue. For that, first of all I would like to share my use case.
My first query was for selecting all the strings from a database and printing the result on page.
$result = mysqli_query($conn, "SELECT * from table_name");
while($row = mysqli_fetch_array($result)){
$string_var = $row["string_name"];
echo $string_var;
echo "<br>";
}
The above code was working as expected and printing all the string_name from the table. Now, if I wanted to use the variable $string_var for another SELECT query in the same table, it was giving me 0 results.
$result = mysqli_query($conn, "SELECT * FROM table_name");
while($row = mysqli_fetch_array($result)){
$string_var = $row["string_name"];
echo "String Name : ".$string_var."";
$sec_result = ($conn, "SELECT * FROM table_name WHERE string_var='$string_name'");
if(mysqli_num_rows($sec_result) > 0){
echo "Has Results";
} else {
echo "No Results";
}
}
In this snippet, my second query $sec_result was always giving me No Results as output.
What I simply did to fix this issue.
$result = mysqli_query($conn, "SELECT * FROM table_name";
while ($row = mysqli_fetch_array($result)){
$string_var = $row["string_name"];
$row_id = $row["id"];
$update_row = mysqli_query($conn, "UPDATE table_name SET string_name='$string_var' WHERE id=$row_id");
}
This step updated all the strings from the table without any hidden/problem causing character.
I am not generalising this approach and I am not sure if this will work in every use case but it helped me fix my issue in less than a minute.
I request #Uueerdo and others with better understanding on this to post a more generic approach so that it can help others because I think many people who can't find a right approach in such conditions, end up using LIKE in place of = but that completely changes the core idea of the query.

Codeigniter Query Builder using MySQL and REGEX with word boundaries adds extra space

With this issue, I would really like to avoid modifying the core files if possible, so a workaround would be extremely helpful.
REGEX works with the 'where' query builder class easy enough, but using the word boundaries breaks it by adding an extra space.
function search($searchQuery){
$sq = '[[:<:]]'.strtolower($searchQuery).'[[:>:]]';
$this->db->select('column');
$this->db->from('table');
$this->db->where('LOWER(otherColumn) REGEXP', $sq);
echo $this->db->get_compiled_select();
}
search('billy');
Expected result:
SELECT column FROM table WHERE LOWER(otherColumn) REGEXP
'[[:<:]]billy[[:>:]]';
Actual result:
SELECT column FROM table WHERE LOWER(otherColumn) REGEXP
[[: < :]]billy[[:>:]]';
This is such a specific issue with a specific stack and I haven't found anybody running into the same issue. I've tried escaping the colons, the <'s, the square brackets, nothing seems to work. Or it adds additional backslashes.
Really any help or direction would be helpful at this point.
Thanks in advance.
function search($searchQuery){
$sq = $this->db->escape('[[:<:]]'.strtolower($searchQuery).'[[:>:]]');
$this->db->select('column');
$this->db->from('table');
$this->db->where('LOWER(otherColumn) REGEXP ', $sq, false);
echo $this->db->get_compiled_select();
}
search('billy');
For Codeigniter v 3.1.6 and MySQL v5.6
Just because Codeigniter adds space before and after < when compiling the query, I do not know why but it does. And I have escaped the value for variable $sq to mitigate injection Attack or identical. Hence, added third parameter to where function as false to prevent it from re-escaping and adding spaces.
I have not gone through other versions of codeigniter. I hope this will work.
For more information on MySQL REGEXP visit this link: MySQL 5.6 Reference Manual - Regular Expressions

Query in PHP with 'and' or 'or' as variable

I would like to do search for advanced search. The Search feature has and/or for every category. User can choose any combination of and n or. Here i give the screenshot
I store the and/or into variable call $pil, $pil1,$pil2 and $pil3. And will put them in query. it's better than validate one by one every condition of and/or
So this is my query using postgresql in PHP
$query = pg_query("SELECT evaluationdate,onlinename,channel,topik,reviewername,sourceevaluation,evaluation
from AgentPerformance
where onlinename like '%".$VEOn1."%'
".$pil." reviewername like '%".$VERev1."%'
".$pil1." channel like '%".$VEChan1."%'
".$pil2."sourceevaluation like '%".$VESource1."%'
".$pil3."evaluationdate between '".$VEStart1."' and '".$VEEnd1."'");
EDIT :
The problem now, All the variables must not be empty or the query will be error. any way to trick this?
You've missed some spaces near sourceevaluation and evaluationdate
Try with this query :
$query = pg_query("SELECT evaluationdate,onlinename,channel,topik,reviewername,sourceevaluation,evaluation
from AgentPerformance
where onlinename like '%".$VEOn1."%'
".$pil." reviewername like '%".$VERev1."%'
".$pil1." channel like '%".$VEChan1."%'
".$pil2." sourceevaluation like '%".$VESource1."%'
".$pil3." evaluationdate between '".$VEStart1."' and '".$VEEnd1."'");
Simply. Use validation for each $pil whether it is empty or not. it makes me validate 4 times, but it solves the problem. The syntax error has been solved too

CodeIgniter inserting apostrophes in to database query

I have a bit of a strange problem that has been baffling me. All I am trying to do is run a query on a database table but for some reason, CodeIgniter is putting apostrophes into the query which is subsequently breaking the page.
My code looks like this:
$this->db->select("SUBSTRING(body,5)");
$this->db->order_by("date", "desc");
$this->data['query'] = $this->db->get_where('blog-entries', array('status' => 'P'), 3);
But I get an error on this page:
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 'FROM (`blog-entries`) WHERE `status` = 'P' ORDER BY `date` desc LIMIT 3' at line 2
The query is actually being run as:
SELECT SUBSTRING(body, `5)` FROM (`blog-entries`) WHERE `status` = 'P' ORDER BY `date` desc LIMIT 3
As you can see for some reason apostrophes have been added around the number 5 within the substring. If I remove the substring then everything works and if I remove the apostrophes and run the query directly on my db it also works.
Has any got any ideas as to why this may be happening or have a solution?
Your help would be greatly appreciated.
Many thanks,
G.
Use this:
$this->db->select("SUBSTRING(body,5)", FALSE);
As a default, Codeigniter tries to add back-ticks where it thinks is relevant. Sometimes it adds them where it shouldn't. Passing FALSE as the second parameter prevents it from doing this.

Categories