Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This may seem like an odd question, and it may have been answered elsewhere...but frankly I'm not quite sure how to phrase a search any better.

Essentially, I am trying to write an entire HTML and Javascript page in PHP (this way I can easily call and manipulate SQL queries...I know it doesn't make a lot of sense, but it's my last resort for an upcoming deadline).

Anyways, I want to call/append to a PHP variable (the SQL query) in my Javascript...Something like this:

mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
$myquery = "SELECT  `xxx`, `yyy` FROM `$tbl_name`";
$query = mysql_query($myquery);
$data = array();

for ($i = 0; $i < mysql_num_rows($query); $i++) {
    $data[] = mysql_fetch_assoc($query);
}

$data1 = json_encode($data);

echo '<!DOCTYPE html>
      <html>
          <head></head>
          <body>
              <script>
                  data_arr = {$data1}
                  ...
                  ...

This doesn't seem to be working though. I've tried:

    data_arr = {$data1}

and

    data_arr = {'.$data1.'}

No luck so far. Is there anything I can do?

share|improve this question
1  
You can't do string interpolation inside single-quote quoted strings. –  Fabrício Matté Apr 25 '13 at 0:25
add comment

2 Answers

Change the quotes to double quotes then use the data_arr = {$data1} one. Single quotes dont recognize values at all.

share|improve this answer
add comment

Try this, this might work:

PHP:

<?php $data1 = "hello"; ?>

JS:

var data_arr = {"<?=$data1?>"}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.