0

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?

1
  • 1
    You can't do string interpolation inside single-quote quoted strings. Commented Apr 25, 2013 at 0:25

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try this, this might work:

PHP:

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

JS:

var data_arr = {"<?=$data1?>"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.