简体   繁体   中英

MySQL query returns no result

I have fields id and date defined as VARCHAR(16)

When I do this query:

SELECT * 
FROM `members` 
WHERE `id` = '4412040999876'
AND `date` = '201706054783'

I get no results.

When I do it like this:

SELECT * 
FROM `members` 
WHERE `id` = 4412040999876
AND `date` = 201706054783

Note - without the quotes - I get the result I am expecting.

EDIT: Here is the code used - I am not manually adding quotes. CI's DB class is adding them.

public function get_member_match($id, $mem, $field = 'name')
{
    $sql = "
        SELECT *
        FROM `members`
        WHERE `id` = ?
        AND `" . $field . "` = ?
    ";
    $sql_array = array($id, $mem);
    $q = $this->db->query($sql, $sql_array);
    return $q->result_array();
}

And I call this function as:

$this->members_model->get_member_match($id, $date, 'date');

I output the query, and the variables are matched correctly, no errors, only the quotes.

Any idea why? I never had this problem before. Working on CodeIgniter 3 using Query Builder.

EDIT2: Summary of findings so far:

  1. Localhost (MySQL 5.6.24) works, server (MySQL 5.5.55-0+deb7u1) doesn't.
  2. The problem occurs in my code and in PHPMyAdmin on the server but works locally, so I eliminate a code issue.
  3. The show variables like 'char%' query shows all character set settings identical on local and on the server.
  4. Database and fields have the same encoding on both server and local.
  5. Does not seem to be a casting issue as many of the comments suggest, as the problem is not present on localhost, only on the server, unless the server has config or other issues.
  6. ...?

id might be defined as integer in your database. To match against integer fields you do not need to use quotes. Quotes are used when you match against string or text fields.

This should cast it back from the codeigniter's auto cast:

SELECT * 
FROM `members` 
WHERE `id` = '4412040999876'
AND `date` = '201706054783'


SELECT * 
FROM `members` 
WHERE CAST(`id` as INTEGER) = '4412040999876'
AND `date` = '201706054783'

Try to use this

$this->db->from('members');
$this->db->where('id',$id);
$this->db->where($field,$mem);
$q = $this->db->get();
return $q->result_array();

It's because the quotes imply that it is a string, whereas id field is an integer and must be written without quotes.

Same for date. Internally date is stored as an integer but is able to convert string into dates as long as they have an appropriate format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM