将数据显示到输入文本字段时出错

I'm having a problem trying to display the data into a input field, instead of display What is on the database it display ' $row[coursename] ', the one that is on the <td> works fine.

Any ideas of How to fix this, I'm really new with php

<?php
 require("coneccion.php");

if(empty($_SESSION['user']))
{
  header("Location: index.php");
  die("Redirecting to index.php");
}

$query = "SELECT courseid, coursename, id FROM courses where courseid = 179";

try
{
  $stmt = $db->prepare($query);
  $stmt->execute();
}
catch(PDOException $ex)
{
  die("Error");
}

$rows = $stmt->fetchAll(); 
?>
<table>
  <tr>
    <th>Name</th> 
  </tr> 
  <?php 
  foreach($rows as $row):   
    echo "<tr>";

      echo '<td><a href="#">' . htmlentities($row['coursename'], ENT_QUOTES, 'UTF-8') . '</a></td>';
      echo '<input type="text" name="coursename" value=" $row[coursename] " />';
      echo '</tr>';

    endforeach;
echo "</table>";

Move the variable outside of the string:

echo '<input type="text" name="coursename" value="' .htmlentities($row['coursename']) . '" />';

You can't add double quotes around it without also adding brackets (but that invovles a lot of error-prone escaping)

echo "<input type=\"text\" name=\"coursename\" value=\"{htmlentities($row['coursename'])}\" />";

This should work:

echo '<input type="text" name="coursename" value=" '.htmlentities($row['coursename']).' " />';