Reputation: 255
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?
Upvotes: 0
Views: 674
Reputation: 2064
Try this, this might work:
PHP:
<?php $data1 = "hello"; ?>
JS:
var data_arr = {"<?=$data1?>"}
Upvotes: 0
Reputation: 2133
Change the quotes to double quotes then use the data_arr = {$data1}
one. Single quotes dont recognize values at all.
Upvotes: 1