CakePHP - 查询返回空字段,如果它有一个特殊字符

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!

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.

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 :)