简体   繁体   中英

Does PHP automatically convert numbers to strings?

I am using dojo and ajax to send a time stamp to PHP, which does a database check, then returns the time stamp for debugging purposes. When I send this time stamp, it's a number, when it is returned, it is a string. Is there a specific reason for this? What should I do to avoid this (cast to int in PHP, fix via JSON, or cast to int in javascript)

Here is the Dojo code

dojo.xhrGet({
 url: 'database/validateEmail.php',
 handleAs: "json",
 content: {
 email : 'George.Hearst@Pinkerton.dw',
 time: 0
 },
 load: function(args) {/*SEE BELOW*/}
});

Here is the PHP script

<?php

/**
 ** connect to the MySQL database and store the return value in $con
 *
 */
$con = mysql_pconnect("localhost:port", "username", "password");

/**
 ** handle exceptions if we could not connect to the database
 *
 */
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

/**
 ** Create table query
 *
 */
mysql_select_db("portal", $con);

/**
 ** Get user entered e-mail
 *
 */
$emailQuerry = mysql_num_rows(mysql_query("SELECT EMAIL FROM user WHERE EMAIL='" . $_GET["email"] . "'")) == 1;

/**
 ** Whether successful or not, we will be returning the time stampe (this is used to determine whether there were any changes between the time a request
 ** was sent, and when this response was returned.
 *
 */
 $result['time'] = $_GET["time"];

/**
 ** Currently only checks to see if the two values were provided. Later, will have to check against passwords
 *
 */
if ($emailQuerry) {
    $result['valid'] = true;
}
else {
    $result['valid'] = false;
}

echo json_encode($result);
?>

And finally the load function left blank above

load: function(args) {
 console.log(localArgs.time + ' v ' + args.time);
 console.log(localArgs.time === args.time);
 console.log(localArgs.time == args.time);
}

The output of which is

0 v 0
false
true

json_encode encodes all variables as a string.

So the javascript will see it as a string.

So in the javascript you could use parseInt(...)

您可以使用json_encode()从PHP(后编码)输出您的数字,使用JSON_NUMERIC_CHECK选项。

To send an integer out as an integer is simple - provide json_encode with one! Put '(int)' around anything that you want converting.

Here's an example:

echo json_encode(array(1, 2, 3));

Output:

[1,2,3]


And another:

$a = '123';
echo json_encode(array($a, (int) $a));

Output:

["123",123]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM