I have stored Swedish words in MysQL database. The encoding of the table is
utf8_unicode_ci
I also tried
utf8_swedish_ci
when I'm doing a search in database, 'a' and 'ä' are treated the same. So the results include both words that begin with a and ä. This is true vice-versa as well.
My application is developed with CakePHP and I have the following in my core.php
Configure::write('App.encoding', 'UTF-8');
Am I missing anything here?
This is my query:
$term = $this->request->query['term'];
$this->loadModel('Words');
$condition = array('word LIKE' => trim($term) . '%', 'is_active' => true);
$words = $this->Words->find('list', array(
'fields' => array('word'),
'limit' => 7,
'conditions' => $condition));
return $this->respond($words, true);
I use to for Jquery autocomplete:
$(function () {
$("#tags").autocomplete({
source: 'autocomplete'
});
});
$query_result = $this->Words->query("SELECT word FROM tbl_words WHERE word LIKE '" . $term . "%' COLLATE utf8_bin LIMIT 7 ;");
This works great for me. Thanks #Mihai for your comment.
I had similar issue. I wanted to list all the autocomplete suggesstions by a tag which may contain swedish characters. I had already a right charset in the mysql database. So no issues there. But I was still failing to search properly from the mysql database with a swedish tag name. However, it turns out to be not related to mysql. I missed to decode the tag in my php backend.
$term = urldecode($this->request->query['term']);
That makes sense, because the jquery autocompate sends out the tag in the url.
Related
A php script I have is extracting data from an XML file to a MySQL database.
It is set-up as followed:
$sql = "INSERT IGNORE INTO `tablename` (columnname) VALUES ('text text text text text text $variablename text text $variablename2 text text')
$variablename and $variablename2 are both variables being extracted from the XML file, and have varying lengths.
So, I know, if I was just dealing with PHP I could use strlen or a variation of (see How to Truncate a string in PHP to the word closest to a certain number of characters? but 'columnname' in my sql database is not a variable.
And 'columnname' is what is limited to the characters.
I set this in mySQL to VARCHAR MAX=106 -- and that works --
But when re-outputting this to my web host it takes the data from the SQL database which is stopped at the maxlength cut-off mid-word.
I want it so that if it does reach the maxlength, the last word is just removed.
Could this be done, perhaps when inputting into the SQL table?
Or even perhaps in the PHP file outputting back to my web host?, such as here:
$rs->data_seek(0);
while($res = $rs->fetch_assoc()) {
$a_topic = array(
"columnname" => $res["columnname"]
or maybe in the $params here?
$params = array(
'status' => $share['columnname'],
Big thanks!
function cut($string, $maxLength)
{
$revertString = strrev($string);
$spaceRevertedPos = strpos($revertString, ' ', strlen($string)-$maxLength);
$revertedCutString = substr($revertString, $spaceRevertedPos);
return strrev($revertedCutString);
}
DEMO
I want to save special characters like the following string in a database:-
:¦:-•:":•.-:¦:-•EXCELLENT!•-:¦:-•:•-:¦:-•:*''•
Below is the code that I am using.
$Fields ['CommentText']=$CommentText;
$Fields = prepareMySQLi($FieldsNotifications,$linkMysqli);
$insert = mysqli_query($linkMysqli,"INSERT INTO `feeds` SET $Fields");
function prepareMySQLi($MyArray,$linkMysqli) {
foreach($MyArray as $col => $val) {
if($val=='Invalid Request') $val='';
if ($val!='' && !is_array($val)) {
$col = mysqli_real_escape_string($linkMysqli,$col);
$val = mysqli_real_escape_string($linkMysqli,$val);
if(isset($fields)) {
$fields .= ", `$col` = '$val' ";
} else {
$fields = " `$col` = '$val' ";
}
}
}
return $fields;
}
But the above code saves the result like:-
•:¨¨:•.EXCELLENT.•:¨¨:••:¨¨:•.
Can anyone guide me how can I save the string same as it is in the database?
It seems like encoding issue. The encoding of the data that you are receiving should be same as the encoding of database where you are storing it.
General practice would be to use "utf-8" encoding for both.
So check in which encoding the database stores the data, and try to convert received data to that format or vice versa.
You can use utf8_encode function for encoding data to "utf-8".
please check by doing these two simple thing, i hope it helps you:-
the "collation" of the column in which you are going to save this data(special characters), made it "utf-8-bin".
either change type of the column to "blob","text" or "long text".
try in your code:- mysqli_set_charset($linkMysqli, "utf8");
encode and decode process. before saving the text encode it and if you want to show it somewhere then first decode it and then show.
simple thing is change
Collation in db to utf8 -> utf8_unicode_ci
and if you dont used field Type as text than change it to text...
May be this is simple solution.....
Other things may You can check your Mysqli Db class Where
'charset' => 'utf8',
is there or not....??
If you dont find charset than please change to utf8...
At last check your page header
and add
<meta charset="utf-8">
Thats it may u will get something...
This question already has answers here:
How can I search (case-insensitive) in a column using LIKE wildcard?
(16 answers)
Closed 8 years ago.
In CakePhp, how MySQL Like works as case insensitive search.
I have tried with following code but problem is also coming here.
If i am searching "Motel Park" then result is fine.
But when searching "motel park" no result is found.
In database Collation is latin1_swedish_ci
$where_condition = array('Ad.completed' => 1,
'Ad.address LIKE '=>'%'.$_REQUEST['address'].'%',
'Ad.status' =>$ad_status
);
$result = $this->Ad->find('all',array('conditions'=>$where_condition));
You can convert both the value to lowercase to use LIKE statement
$where_condition = array(
'Ad.completed' => 1,
'LOWER(Ad.address) LIKE '=>'%'.strtolower($this->request->data['address']).'%',
'Ad.status' =>$ad_status
);
$result = $this->Ad->find('all',array('conditions'=>$where_condition));
try using "COLLATE utf_general_ci" collation. refer this link.
but there is an easy solution , by converting all string in to lowercase. then check.
$request_address=strtolower($_REQUEST['address']);
$where_condition = "Ad.completed = 1 AND
LOWER(Ad.address) LIKE '%".$request_address."%' AND
Ad.status ='".$ad_status."'";
$result = $this->Ad->find('all',array('conditions'=>$where_condition));
MY AIM
Use jQuery UI Autocomplete to search for a book and when a book is clicked from the suggestion dropdown, populate the remainder of the HTML form with details of the book selected by using the select function of the autocomplete.
THE PROBLEM
As long as the returned data does not contain a line break (I have a table field called description in the database and it has line breaks in the stored data ) the autocomplete works like a charm. But if I include the description field data into the returned array, the suggestion dropdown fails to show up. However when checked with Firebug, data is being returned; just not showing up
THE CODE
// STORING INFORMATION FROM THE DATABASE
$items[$r['book_id']] = array('name'=>$r['book_name'],
'category'=>$r['c_id'],
'author'=>$r['book_author'],
'vendor'=>$r['book_publisher'],
'edition'=>$r['book_edition'],
Culprit here --> 'description'=>$r['book_description'],
'price'=>$r['book_price'],
'date'=>$r['date']);
// DATA FOR POPULATING THE HTML FORM (USING ui.item.<index name>)
$result = array();
foreach ($items as $key=>$value)
{
array_push($result, array("id"=>$key,
"label"=>$key."-".$value['name'],
"value" => strip_tags($value['name']),
"name" => $value['name'],
"cat" => $value['category'],
"author" => $value['author'],
"vendor" => $value['vendor'],
"edition" => $value['edition'],
"description" => $value['description'],
"price" => $value['price'],
"date" => $value['date']));
}
// $result is then supplied to a function which converts the data to json
If I remove the description entry from the $items and $result arrays, everything works as expected. I tried a couple of things after going through SO threads here:
WHAT I TRIED
Tried str_replace('\n', '\\n', $r['book_description'])
Tried str_replace('<br />', '\\n', $r['book_description'])
Out of frustration even tried urlencode($r['book_description'])
But none of them seemed to work. Is there a workaround for this one?
Thanks in advance.
UPDATE
Using json_encode on the returned set is resulting into:
Are you using json_encode()? ..It should escape everything for you. You could also try something like
$newDesc = str_replace(PHP_EOL, "", $r['book_description']);
or
$newDesc = str_replace(chr(10), "", $r['book_description']);
$newDesc = str_replace(chr(13), "", $newDesc);
Escape sequences (\n \r \t etc...) only works with double quotes.
Replace:
str_replace('\n', '\\n', $r['book_description'])
For this one:
str_replace("\n", "\\n", $r['book_description'])
and then works
Sorry for my bad english.
I need to find all schools with contains a certain emailaddress in a string
At this moment, I'm sending a query to my database to obtain a list of Schools like this
$aSchools = School::model()->findAllByAttributes(array(
'finished' => School::SCHOOL_CREATED,
));
After that, I itterate over all the schools to check if they containt the mailAddress like this:
$aFoundSChools = array();
foreach($aSchools as $oSchool)
{
if (strpos($oSchool->mailAddress, Yii::app()->user->mailAddress))
{
$aFoundSChools [] = $oSchool;
}
}
But I'm guessing this could be cleaner, right? Can i do that in a single function, like a 'LIKE' query in sql?
MongoDB supports "like" queries in the form of regular expressions. Be warned though that this can not use an index. From plain PHP, you'd construct it like this:
$query = array(
'finished' => School::SCHOOL_CREATED,
'mailAddress' => new MongoRegexp( '/' . addslashes( Yii::app()->user->mailAddress ) . '/' ),
);
You'll have to use the addslashes if you think your mail address might contain a /.
I don't quite know Yii, but I expect you can use $query like this, just replacing your already existing test for just 'finished':
$aSchools = School::model()->findAllByAttributes( $query );