MySql - bigints, php and auto string/int casting f

2019-09-08 07:06发布

问题:

I asked a question about bigints yesterday which was kindly answered. However, I have been observing some weird behaviour and would like to understand what is going on.

In my php I have an array which I send back to a javascript web client program which uses it.

In the php

    sendBack = null;
    sendBack[0]['TimeStamp'] = $Time; // A bigint got from a mysql table milliseconds from 1970
    sendBack[0]['Text'] = $Message; // A varchar message got back from mysql
    // I am guessing at this point you have worked out this is a text-chatroom thing going on
    sendBack[1]['TimeStamp'] = 0; // A zero indicates an admin issue - note its an int but a small one
    sendBack[1]['Text'] = $MessageAdmin;

    // And I pack it up to send back
    echo json_encode($sendBack);

In the js I unpack it to use with:

    var json = eval('(' + data + ')');

The problem is, the 0 index TimeStamp in the js is being treated as a string but the index 1 Timestamp is being treated as an int.

From an educational point of view does anyone know what is going on?

回答1:

I believe values returned from a database with PHP are always strings. In order to convert your zero-index timestamp you'd need to do something like:

sendBack[0]['TimeStamp'] = parseInt($Time, 10);

which will convert it to an integer value (base-10).

Obviously the 1-index timestamp is being set as zero directly hence the reason it's returning as an int.