Reputation: 53
This code is when i hardcore the sentence "Have a nice day!", it will echo out the exact same line. My question is what if i want to retrieve sentence from the database, instead of hard-coding it.
<?php
$php_var = "Have a nice day!";
?>
<html>
<head>
<title>Hello</title>
</head>
<body>
<script>
var js_var = "<?php echo $php_var; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
</body>
</html>
I am suppose to do something like this is it? but it cant work. It printed out "SELECT * FROM sen WHERE id=1 ;"
on the page.
<?php
$con = mysql_connect(localhost,root,password,database_name);
$php_var = "SELECT * FROM sen WHERE id=1 ;";
?>
<script>
var js_var = "<?php echo $php_var ; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
Upvotes: 0
Views: 87
Reputation: 450
You're not executing the query and fetching the result. Something like this should work:
<?php
$con = mysqli_connect(localhost,root,password,database_name);
$php_var = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM sen WHERE id=1 LIMIT 1"));
?>
<script>
var js_var = "<?php echo $php_var['id']; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
Please be aware of some things:
mysql_*
to mysqli_*
, this because mysql_*
is deprecated and will being removed in the future.Upvotes: 4
Reputation: 130
Remove ; from the query.
Use $php_var = "SELECT * FROM sen WHERE id=1";
Upvotes: 0
Reputation: 400
My suggestion is that you create a Rest api with json response backend in PHP and then have a javascript frontend using like JQuery $get or something.
Upvotes: 0