Page 1 of 1

add php variable into <title> html tag

Posted: 11 Jul 2017, 13:54
by JanMolendijk
I run your Website Mini-Traffic and Pages Access data:
https://coursesweb.net/php-mysql/website ... ss-data_s2

From my mebers page Users.php i don`t get an title from database.
I added simple an <title>, and i`m very supriced i cant add php code into <title>.
in this code it does not show value of $users['name'].
i tried also echo php also not working:

Code: Select all

<?php 
include('../connection.php');

$id = (int) $_GET['id'];
$sql=mysqli_query($conn,"SELECT * FROM `user` WHERE id='" . $id . "' ");
$users=mysqli_fetch_assoc($sql);
?>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<title>Profile View '. $users['name'] .'</title>

<script>
function myFunction() {
    var x = document.getElementsByTagName("TITLE")[0].text;
    document.getElementById("demo").innerHTML = x;
}
</script>

add php variable into <title> html tag

Posted: 11 Jul 2017, 16:47
by Admin
Hello,
Add the php variable into <?php .. ?>, with "echo".
Try this:

Code: Select all

$sql=mysqli_query($conn,"SELECT * FROM `user` WHERE id='" . $id . "' LIMIT 1");
$title ='Defaul Title';
if(mysqli_num_rows($sql)>0){
  while($row=mysqli_fetch_assoc($sql)) $title = $row['name'];
}
?>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<title>Profile View <?php echo $title; ?></title>