0

Hi guys can't seem to use MySQL row values in JavaScript. I've tried all kinds of quote and double-quote combinations.

$sql = "SELECT desk_id, desk_x, desk_y FROM desks";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo '<script type="text/javascript">';
        echo 'new Desk('$row["desk_id"]', '$row["desk_x"]', '$row["desk_y"]')';
        echo '</script>';
    }
} 

I'm getting this error:

Parse error: syntax error, unexpected '$row' (T_VARIABLE), expecting ',' or ';'

Thanks for any help.

Edit: Thanks for the answers guys.

This works:

while($row = $result->fetch_assoc()) {  
    echo '<script type="text/javascript">';
    echo "new Desk('{$row["desk_id"]}', '{$row["desk_x"]}', '{$row["desk_y"]}')"; 
    echo '</script>';            
}

When I try to put the open and close tags outside of the while loop I get the error:

SyntaxError: Unexpected token new

Adam Stück
  • 107
  • 11

4 Answers4

2

In order to prevent the need to escape characters ; In PHP, string concatenation is done with the . (period)

echo 'new Desk('.$row["desk_id"].', '.$row["desk_x"].', '.$row["desk_y"].')';

Or

echo "new Desk('{$row["desk_id"]}', '{$row["desk_x"]}', '{$row["desk_y"]}')"; 
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Timothy Groote
  • 8,614
  • 26
  • 52
1

It's not the best way to deal with php and javascript.. It would be much better to do ajax call.

If you want to put php variable into string please try this way:

echo 'new Desk('.$row["desk_id"].', '.$row["desk_x"].', '.$row["desk_y"].')';
Kacpers
  • 11
  • 2
1

1st : Move your script tag to outside the while loop

2nd : use escape character (\) or use double quotes like this

if ($result->num_rows > 0) {
    echo '<script type="text/javascript">';
    while($row = $result->fetch_assoc()) {

        echo "new Desk('{$row["desk_id"]}', '{$row["desk_x"]}', '{$row["desk_y"]}')";

    }
     echo '</script>';
} 
JYoThI
  • 11,977
  • 1
  • 11
  • 26
1

Messing up javascript with PHP is discouraged. You could use AJAX calls.

As per your question, if you want to enquote the javascript input parameters, you have to escape them properly with backslash:

echo 'new Desk(\''.$row["desk_id"].'\', \''.$row["desk_x"].'\', \''.$row["desk_y"].'\')';

But if you are sure your parameters are numbers, you don't need to enquote them:

echo 'new Desk('.$row["desk_id"].', '.$row["desk_x"].', '.$row["desk_y"].')';
mighTY
  • 188
  • 8