1

I've looked through various other questions on SO, but can't quite get the right answer. Basically, I have an array that needs data from a MySql database. Here's what I've tried:

var $name = "Foo",
    $x = 10,
    $bar =
      <? php
        $barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
        $barArray = array();

        while ($r = mysql_fetch_assoc($barQuery))
        {
          $barArray[] = $r['item'];
        }

        echo json_encode($barArray);
      ?>;

EDIT: I then post this to a .php file, and print the returned data:

$.post("file.php", {bar: JSON.stringify($bar), name: $name}).done(function(data)
{
  $('body').html(data);
  window.print();
  setTimeout("location.reload(true)", 500);
});

However, I get an error saying "syntax error, unexpected T_VARIABLE". Is it not possible to populate a JS array this way, or is there another way to do it?

Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
Michael Jarvis
  • 1,115
  • 3
  • 10
  • 17

2 Answers2

0
var $name = "Foo",
    $x = 10,
    $bar = "
      <?php
        $barQuery = mysql_query("SELECT item FROM table WHERE name = '$name' AND number = '$x'");
        $barArray = array();

        while ($r = mysql_fetch_assoc($barQuery))
        {
          $barArray[] = $r['item'];
        }

        echo json_encode($barArray);
      ?>";
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
0

You have a superfluous space inside the PHP opening tag:

      <? php
        ^--- this shouldn't be there

As it stands, the <? is parsed as a short open tag, and so the php is parsed as a(n undefined) constant, which is immediately followed by $barQuery—hence the syntax error that you see: unexpected T_VARIABLE.

eggyal
  • 122,705
  • 18
  • 212
  • 237
  • It's always something so simple... Thanks! However, an error in the JS console is saying there is an 'unterminated string literal' when I declare `$bar` – Michael Jarvis Mar 07 '15 at 14:27
  • @MichaelJarvis: That's strange. Have you changed your code from what it originally was in your question? Check the JavaScript that is output by PHP (and therefore parsed by the browser); your JS console might help to pinpoint the problem. – eggyal Mar 07 '15 at 14:29
  • Yes, here's what it said: `$bar = "
    Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/page.php on line 791
    []";` Line 791 is where the `while` loop begins
    – Michael Jarvis Mar 07 '15 at 14:34
  • @MichaelJarvis: That means that `$barQuery` is false, because `mysql_query()` failed. You should inspect `mysql_error()`. See http://stackoverflow.com/questions/2973202/mysql-fetch-array-expects-parameter-1-to-be-resource-or-mysqli-result-boole – eggyal Mar 07 '15 at 14:49