A
A
Andrey Amsteady2017-04-12 03:46:01
PHP
Andrey Amsteady, 2017-04-12 03:46:01

MySQLi: how to store data types in result set (array)?

Good day.
A simple select query returns an array of data, where each array element is a string. The code:

$r = $mysqli->query ("SELECT `id`, `name` FROM `users`");
$r->fetch_all (MYSQLI_ASSOC);

// вернет подобный результат
array (
'id' => '10',
'name' => 'Василий'
);

Is it possible to get a result set while preserving data types (int, string)? If so, which mysqli function bundle should I use? If not, the question is more educational: why does mysql behave like this?
By the way, the results of the prepared query are returned “as I need it”, that is, the data type is saved:
$r = $mysqli->prepare ("SELECT `id`, `name` FROM `users` WHERE `id` > ?");
$uid = 5;
$r->bind_param ('i', $uid);
$r->execute ();
$r->get_result ();

// вернет подобный результат
array (
'id' => 10,
'name' => 'Василий'
);

Solution: setting the appropriate option.
$db = new mysqli ('localhost', 'root', '', 'mytests');
$db->options (MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2017-04-12
@amsterdy

sql
CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `amount` float DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `users` (`id`, `name`, `amount`)
VALUES
  (1,'user1',11.589),
  (2,'user2',478.541),
  (3,'user3',0.258);
php
$db = new mysqli('localhost', 'root', '', 'mytests');
$db->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$query = 'SELECT * FROM users';
$result = $db->query($query);
while($row = $result->fetch_assoc()) {
  var_dump($row);
};

array(3) {
  'id' =>
  int(1)
  'name' =>
  string(5) "user1"
  'amount' =>
  double(11.589)
}
array(3) {
  'id' =>
  int(2)
  'name' =>
  string(5) "user2"
  'amount' =>
  double(478.541)
}
array(3) {
  'id' =>
  int(3)
  'name' =>
  string(5) "user3"
  'amount' =>
  double(0.258)
}

but, frankly, I don't understand what makes people cling to mysql/mysqli when there is pdo.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question