0
<script>
$(function() {
    var name = [

        <?php

        $Database = "database name";
        $DatabaseUserName = "db_user";
        $DatabasePass = "db_pass";

        $connect = mysql_connect("~", $DatabaseUserName, $DatabasePass);
        @mysql_select_db($Database) or ("Database not found");

        $query = "SELECT ~ FROM ~";
        $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());

        while ($row = mysql_fetch_array($result)) {
        echo "\"". $row['~']."\", ";
        }

        // $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());

        mysql_close($connect);

        ?>
    ];

    $( "#~" ).autocomplete({
        source: name
    });
});
</script>

Basically, I'm getting correct output except the closing PHP tag "?>" is included in the output when I don't want it to be. Is there a better way to do this?

bob
  • 235
  • 2
  • 3
  • 12
  • What is your current output and what is the expected output? – Rizier123 Feb 10 '15 at 06:14
  • current output: an autocompleting combobox that fills in as user types, but with the closing "?>" PHP tag to the right of the box – bob Feb 10 '15 at 06:16
  • expected/output I'm seeking: same output minus the closing "?>" PHP tag to the right of the combobox – bob Feb 10 '15 at 06:16
  • Check your data for `?>` in it – sectus Feb 10 '15 at 06:28
  • sectus that's exactly what it was... I had a leftover ?> tag in the body of my html... thanks for responding everyone! – bob Feb 10 '15 at 06:36

2 Answers2

1

Use json_encode() to output JavaScript safe data. For example...

<script>
<?php

// connect, query, etc

$data = [];
while ($row = ...) {
    $data[] = $row['~'];
}
?>

var name = <?= json_encode($data) ?>;
</script>

Here's a simplified demo ~ eval.in


And of course, here's the obligatory "don't use the deprecated mysql extension, etc" addendum.

Community
  • 1
  • 1
Phil
  • 157,677
  • 23
  • 242
  • 245
  • thank you for the respone, I found my error... I had a leftover ?> tag in the html body – bob Feb 10 '15 at 06:37
-1

Run this code and check if it is still coming. I could not reproduce the error.

<html>
<head>
<script>
    var name = [

        <?php


        $row=array("Volvo", "BMW", "Toyota");
        for($i=0;$i<count($row);$i++) {
        echo "\"". $row[$i]."\", ";
        }



        ?>
    ];
</script>
</head>
<body>
</body>
</html>