using the title to get data from the database codeigniter - php

I made a code using codeigniter to get the data by the title of the topic. my code is.
the controller
public function viewTopic($category, $title){
$data['topic'] = $this->Setting->get_dataNew('*', 'community_topics', 'WHERE title="'.str_replace('-', ' ', urldecode($title)).'"');
}
the link is like this one.
/community/questions/ما-هو-المجتمع-؟
The problem is when I added a special characters to the title like - or () the query not working, is there is a way to fix it ?

Because you are using the - to remove the spaces it will not be possible, unless you used different symbol for it, codeigniter filters all special characters to prevent the sql injection attacks, however, you can add column named urlSlug, and store the exact value of the slug in it, so when you query next time, it will be
public function viewTopic($category, $title){
$data['topic'] = $this->Setting->get_dataNew('*', 'community_topics', 'WHERE urlSlug="'.$title.'"');
}
We are using the same for the Arabic version of the website, and it is working perfectly,
also don't forget you will need to add the list of the permitted characters to
$config['permitted_uri_chars']='' to avoid any future error.

Related

No results when search term include '(' in codeigniter query

I'm trying to search string using CI model. Here is the code written for it.
$test_name = "TSH ( Thyroid stimulating harmone)";
$this->db->like('test_name',$test_name);
Above query when executed gives me zero result. But if I change my database column and replace '(' by '{' or something else then it shows results by executing above code.
new $test_name variable becomes "TSH { T..."}.
But the requirements is to use the string containing '(' only.
How should i carry forward?
Please do let me know if additional information is required.
I don't think like() will help you much with your search needs. you use a where() function containing with LIKE clause.
$keyword="TSH ( Thyroid stimulating harmone)";
$this->db->select('*')->from('table')->where("column LIKE '%$keyword%'")->get()->result_array();

Codeigniter query with special character

I am using codeigniter 3 for my project. In my database i have a table that is being used by some other authentication system. the problem i am facing when i am am searching some value with special character (inside the data/ concated with the data)
$query = "SELECT * FROM tablename WHERE value = '$#!"."asdasd<3ddasd"."'";
Even $this->db->query($query); is not returning any desirable output. after echo $this->db->last_query(); i get the query and it was as it should be. if i copy it to phpmyadmin, it gives correct result.
As per several discussion in SO and some other pages i have also tried with
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-!##<$';
db is utf8_general_ci is Server connection collation.
Query i put here just for showing you a scenario and i have used active record.
EDIT 1: I have used $this->input->post() for getting the input.
EDIT 2: just found out doesnot work with "$#!"."asdasd<3ddasd" but work for "$#!"."asdasd3ddasd"
Make sure you do not forget to urldecode the post values. What might be happening is that you use $_POST instead of the codeigniter function $this->input->post();
$_POST won't urldecode the parameters for you while the codeigniter function does.
So verify that the variable you pass to your query really is selänne and not sel%C3%A4nne
And if it is sel%C3%A4nne, use urldecode() or $this->input->post()
Reference from This Question

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

Php: I need to insert one & within my mysql database

I'm having trouble with the ampersand symbol, because I've to allow user to insert page_title within database.
The problem is that in my mother language many companies have the symbol in their names like per example "Santos & Filhos".
The question is, how can I insert this, without break my database and without opening security issues?
using this the database gets broken
$title = preg_replace('/&/', '&', $title);
$final_title = utf8_encode($title);
I'm using utf8_encode because of the other accents like á or ã
Thanks, hope you can help me here
EDIT
ok, first thanks to all, most of you were wright, mysql_real_escape_string is indeed one of the best options, if not the best.
I discovered that I was missing one escape (in query) before post my variables to be processed by php and inserted within the database.
So I manage to get my & but now I can't manage to have accents...
So far my php code looks like this
$title = mysql_real_escape_string($_POST['title']);
$sql = "UPDATE bodytable SET body_title = '".utf8_encode($title)."'";
and then in my frontage I've
utf8_decode($row['body_title']);
the result is
<title>Santos & Filhos - Repara?es de autom?veis</title>
Escape characters going into the database with something like mysql_real_escape_string() or PDO and use htmlentities() when displaying it.
This covers securing user input: What's the best method for sanitizing user input with PHP?
Try using an escape character in front of all your special characters you want to insert in the database. Encoding is ok but for example, if the following string was to be added to mysql string field you would get an error.
"special characters don't work"
And you can do this to prevent these errors
"special characters don\'t work"
I belive there is a methods called addslashes(string x) and stripslashes(string x) that will do that for you.
$title_to_insert_in_database = $str = addslashes($title);
$title_for_page = htmlspecialchars($title_from_database);

SELECTing MySQL rows with unusual characters using PHP and querystrings

Table name Styles.
Referenced Column: Style
Coding with PHP 5.
Problem:
My SELECT query to MySQL returns 0 rows.
I'm using the column name in querystring as identifier (something like example.com.php?style=paper-pencils). For SEO purposes I've removed any odd characters and replaced spaces with '-'. Using url rewrite to end up with example.com/paper-pencils.
Working on a database I inherited which uses characters such as '&' or ':' in the Style column. On the database side, the Style column would contain a row with something like "Paper & Pencils" as compared to my slugged version of "paper-pencils".
Things I've Tried:
I de-slug the url so i end up with 'paper pencils' (see below in query example).
I tried
SELECT * ,REPLACE( 'Style', '&', ' ' ) AS Style, REPLACE( 'Style', ':', ' ' ) AS Style FROM Styles
WHERE Style = 'paper pencils'
to no avail. The query I have runs fine, it just comes back with 0 results.
My next step would be to do a PHP SWITCH statement. Something like
case: $_GET['style'] = 'paper-pencils'
$DBstyle = 'Paper & Pencils' but I feel like there has to be some other way around it. I have 30 different possibilities and would prefer something better.
Any suggestions on how I can account for these unusual characters with random occurrences?
Maybe you can add another column to this table called style_slug. This column will contain the slugged version that you use in your urls and will allow you to retrieve the Style column in your query.
Just like Gohn said or, a better one - use an approach which is used on this site - have both an unique identifier and a slug in the url.
example.com/2356356/paper-pencils
will cajole SEO and make your life easy.

Categories