Note that there are some explanatory texts on larger screens.

plurals
  1. POBoolean values in MySQL, Perl DBI, and JSON
    primarykey
    data
    text
    <p>Consider a simple mysql table with columns <code>id</code> (an integer) and <code>flag</code> (a boolean). A user interface written in JavaScript communicates to a CGI backend via JSON, both for receiving data from the table and for updating it.</p> <p>Now, when sending the data <code>{id: 5, flag: true}</code> to the server, I of course use <code>from_json</code> to get a perl hash(ref). Then </p> <pre><code>my $sth = $dbh-&gt;prepare('UPDATE my_table SET flag = ? WHERE id = ?); $sth-&gt;execute($data-&gt;{flag}, $data-&gt;{id}); </code></pre> <p>always results in a false value being inserted. I believe this is because of the magic behaviour of JSON::true and JSON::false, which stringify to 'true' and 'false', respectively (but would numify to 1 and 0). Apparently, the execute statement provides string context, and not numeric context, so the mysql server receives a string containing no numbers, which then causes the value 0 to be inserted. For now, I fix this by putting <code>? 1 : 0</code> after <code>$data-&gt;{flag}</code>.</p> <p>In the other direction, the opposite wrong thing happens: According to DBI's doc, "Most data is returned to the Perl script as strings.", so when I hit the result of a SELECT query with <code>to_json</code>, the values are received by the UI as JavaScript strings "0" and "1", which are both true in JavaScript. So for now I do a <code>$_-&gt;{flag} += 0 foreach (@result)</code> before applying <code>to_json</code>.</p> <p>Question: At which point(s) in the chain should I insert these 'hacks'? In the JavaScript end, I could for example make sure to send the values 1 and 0 instead for true and false, and reread the flags as numbers. Is there something I can tell DBI to make it return numeric columns as (scalars which JSON would consider as) numbers? </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload