CakePHP - query returns empty field if it has a special character in it

允我心安 提交于 2019-12-10 04:22:39

问题


I have what I think to be a normal query-call in CakePHP - it works for all results, but when a field has a special character in it, the field will return empty. It doesn't break - and it still gives me the rest of the fields - it's just that one field that's empty.

Example:

$this->paginate = array(
'conditions' => array(
     'Item.name != ' => '',
),
);
$data = $this->paginate('Item');

This will return all the items in my table (including the one that I thought had an empty name field) - but when I try to echo the name to the page, it works for every item except the one with a special character (é). I changed it to a normal "e" and it shows up fine.

How can I return results even if they have a special character in their name? Thanks in advance!


回答1:


Check to make sure your database uses the right encoding (UTF-8, ideally) and you have configured Cake to use this same encoding as well in config/database.php:

class DATABASE_CONFIG {
    public $default = array(
        ...
        'encoding' => 'utf8'
    );
}

If you have some encoding mismatch, your app has probably stored garbage in the database already, so make sure you test with the right data and/or a fresh database.




回答2:


This is probably less of a Cake-specific issue and more of a PHP / MySQL issue. (Others have already brought up encoding, so I'll skip that.)

Single quotes means a literal string being handed to MySQL: 'Item.name != ' => ''

PHP (a la Cake) probably parses that string quite literally. In fact, it's might even be parsing it like:

"Item.name != "

(note there's nothing after the operand? and if it falls last in the SQL query, the query wouldn't error, it would probably still work!)

When you meant for it to test:

"Item.name != ''"

(note empty single quotes now included in the string)

However, since you're not getting an error - and the rest of the data pulls! - you probably want to edit that statement, because your problem is more likely syntax.

'Item.name IS NOT NULL'
'Item.name <> ' => ''
'Item.name IS NOT' => ''

Give those a try.

http://dev.mysql.com/doc/refman/5.6/en/comparison-operators.html describing IS NOT NULL vs IS NOT (bool) vs <> and != (is not equal to).

HTH :)



来源:https://stackoverflow.com/questions/5610123/cakephp-query-returns-empty-field-if-it-has-a-special-character-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!