从PHP中的查询获得相同的错误结果

I have one problem, when i do my query I always get same result (2), it doesn't get right ID value:

    $query = $this->mysqli->real_escape_string("SELECT id FROM image WHERE file_name = ?");

    $stmt = $this->mysqli->prepare($query);
    $stmt->bind_param("s", $this->name);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id);

    if($stmt->num_rows == 1)
    {
        var_dump($stmt->id);
        var_dump($id);
    }

Result is always:

$int(2)
NULL

And I dont even have that ID value in that table. Notice: This query works in phpmyadmin.

Please RTM how to use mysqli:

$stmt = $this->mysqli->prepare("SELECT id FROM image WHERE file_name = ?");
$stmt->bind_param("s", $this->name);
$stmt->execute();
$stmt->bind_result($id);
$stmt->fetch();

var_dump($id);
  • you don't escape the whole query
  • you don't need store_result
  • you need fetch
  • you need to var_dump the variable you have bound, not some other variable like $stmt->id

You don't need to use the escaping function, especially on the whole query string. That's a low-level function for exceptional circumstances.

Putting the query directly into the prepare call should fix it.