Consider a simple mysql table with id (integer) and flag (boolean) columns. The user interface, written in JavaScript, communicates with the CGI server via JSON, both for receiving data from the table and for updating it.
Now, sending the data {id: 5, flag: true} to the server, of course I use from_json to get the perl (ref) hash. Then
my $sth = $dbh->prepare('UPDATE my_table SET flag = ? WHERE id = ?); $sth->execute($data->{flag}, $data->{id});
always leads to the introduction of a false value. I believe this is due to the magical behavior of JSON :: true and JSON :: false, which build true and false, respectively (but will be numbered 1 and 0). Apparently, the execute statement provides a string context, not a numeric context, so the mysql server gets a string containing no digits, which then calls the value 0. At the moment, I fix this by putting ? 1 : 0 ? 1 : 0 after $data->{flag} .
The opposite happens in the other direction: according to the DBI document, βMost of the data is returned to the Perl script as strings.β, So when I click on the result of the SELECT query with to_json , the values ββare accepted by the UI as JavaScript strings β0β and β1β, which are true in javascript. So now I do $_->{flag} += 0 foreach (@result) before applying to_json .
Question: At what point (s) in the chain should I insert these "hacks"? At the end of JavaScript, I could, for example, be sure to send the values ββ1 and 0 instead of true and false and re-read the flags as numbers. Is there something I can tell DBI to return the numeric columns in the form (scalars that JSON would take into account)?
json mysql perl dbi
Villemoes
source share