سؤال

I use this to create a unique code for each product in my store,

echo base_convert(uniqid(),16,10);

For instance,

1403802682572650

My query is simple like this,

        $sql = "
            SELECT * 
            FROM page AS p

            LEFT JOIN stock AS o
            ON o.id = p.page_id

            WHERE p.type = ?
            AND p.hide != ?
            ORDER BY p.backdated_on
        ";

And when I want to get the product code, I do this,

var_dump($product->code);

But PHP returns float(1.4038026825726E+15) instead of 1403802682572650

Why does PHP returns float instead of string? How can I get the number as it is?

Or should I convert/cast the number to string or varchar in my SQL query before requesting result from the db table?

EDIT: Found the bug in my code.

I have a line to convert json to array and that convert the string into float, for instance,

echo json_decode("1403802682572650", true); // 1.4038026825726E+15
هل كانت مفيدة؟

المحلول

The value is out of range.

PHP Man:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

نصائح أخرى

No. You should change the column itself to VARCHAR since it's not really being used as a number.

You can do one of two things without making possibly harmful changes to the database schema.

You can first type cast $product->code:

var_dump( (string) $product->code );

Or you can cast/convert the select in the query:

SELECT CAST(columnName as char) as code ...

I've always been a fan of handling most changes like this via the code rather than the query, in the event that a database engine doesn't support your query.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top