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>
-
1currently you only assign your query to a variable you're supposed to run it on your connection and then extract the result, im currently looking up how to do this again.kpp– kpp2014年06月25日 06:53:45 +00:00Commented Jun 25, 2014 at 6:53
-
Is this question answered?Wouter0100– Wouter01002014年06月27日 06:57:30 +00:00Commented Jun 27, 2014 at 6:57
3 Answers 3
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:
- Don't forgot error handling on the right way. (Not or die)
- Check if the MySQL connecton was successfully made.
- Possibility of MySQL injection
- I've updated
mysql_*tomysqli_*, this becausemysql_*is deprecated and will being removed in the future.
4 Comments
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.
1 Comment
Remove ; from the query.
Use $php_var = "SELECT * FROM sen WHERE id=1";
1 Comment
; doesn't matter. And whole mysqli_query() and mysqli_fetch_assoc() are missing. Read Wouter0100's answer.