Search code examples
javascriptphpmysqlvar

mySQL TIMEDIFF Query to JS var - Error because of colons


How can I pass the results of my MySQL Query using TIMEDIFF to a Javascript var in the same PHP file? I want to use the result as a text string label. I get a browser error because of the colon in the passed data.

MySQL:

$mytimediff = 'TIMEDIFF(NOW(), DBTimeStamp) as myTimeDiff';        
$querylast = "SELECT *, $mytimediff FROM user_log ORDER BY LogID DESC LIMIT 1";
$resultlast = mysql_query($querylast);
$rowtimediff = $rowlast['myTimeDiff'];

JS:

var rowage = <?php echo $rowtimediff ?>;

This results in the browser console error:

"Uncaught SyntaxError: Unexpected token :"

Console error output example showing the colons: "var rowage = 00:00:43;"

All other MySQL operations and variables pass ok.


Solution

  • Json-encode a PHP variable when printing if you want to use it in Javascript.

    <?php
        $rowtimediff = ['foo' => 1, 'bar' => 2, 'baz' => 3];
    ?>
    <script>
        var rowage = <?= json_encode($rowtimediff) ?>;
        console.log(rowage);
    </script>
    

    As a result, you will get a valid Javascript code:

    <script>
        var rowage = {"foo":1,"bar":2,"baz":3};
        console.log(rowage);
    </script>
    

    Additionally, when working with strings, you can simply wrap that PHP injection in quotes (numbers doesn't require quotes) like that:

    var rowage = "<?= $rowtimediff ?>";