3

I know when MySQL returned data, it is returned as strings, no metter of the MySQL data type.

So why when i run this prepared statement i get a integer ?

    $id = '1';

    sql = "SELECT * FROM
            USER
            WHERE user_id = ? ";

    $stmt = $this->conn->prepare($sql);
    $stmt->bind_param('i', $id);
    $stmt->execute();

    $user = $stmt->get_result();

    return ($user->num_rows == 1) ? $user : NULL ;


    if ($user) {

    while($row = $result->fetch_assoc()) {
        $data = array();
        $data["user_id"]      = $row["user_id"];

    return $data; 

When i run php gettype($data['user_id']) i get an integer.

I thought that datatype will always be converted to a string.

yakir30
  • 53
  • 5
  • The `'i'` is telling the mysqli binding function that this database column is an integer and `$id` should be treated as such when the parameter is replaced by this value. It is not describing what the contents of `$id` are – RiggsFolly Feb 19 '17 at 09:28
  • the contents of the variable $id = '1' – yakir30 Feb 19 '17 at 09:32
  • ??? Who said that it always returns a string ??? – JordanH Feb 19 '17 at 09:33
  • @RiggsFolly So if i replace 'i' to 's' the query will work? beacuse the id column in database are integer. – yakir30 Feb 19 '17 at 09:35
  • @JordanH look at this questions [link](http://stackoverflow.com/a/5323169/7587802) – yakir30 Feb 19 '17 at 09:37
  • by the way, the last `if` statement won't be executed and your function will return `NULL` when there are zero or more than one result :) – niceman Feb 19 '17 at 10:03
  • also how did you know that you got an integer, php is dynamically typed you know :) – niceman Feb 19 '17 at 10:04
  • No, if the database column is an interger use `i` and whatever is in ` $id` will be correctly passed to that field by the middle ware involved with the MYSQLI extension – RiggsFolly Feb 20 '17 at 00:12

1 Answers1

2

It does not always return as string. Maybe you are using PHP version upper than 5.3( the version of PHP 5.3 is compiled with mysqlnd (and not old libmysql)), uses mysqlnd as the native driver and the native driver returns integer types appropriately. Please check which version you are currently using. For more details you can go through this link. http://blog.ulf-wendel.de/2008/pdo_mysqlnd-the-new-features-of-pdo_mysql/

Tasnim Fabiha
  • 1,148
  • 1
  • 17
  • 31
  • 1
    This is break my app, when i use the mysqli non prepared statement i always get a string, and now when i moved to prepared statement i always get a integer no metter if i passed $stmt->bind_param('s', $id); $_SESSION['id'] === $_GET['id'] not ture. – yakir30 Feb 19 '17 at 10:39
  • even now it is still breaking, sometimes is string, sometimes is integer, it seems to be a bug? – Jones G Sep 03 '20 at 14:48