Arjun Chaudhary Arjun Chaudhary - 2 months ago 14
MySQL Question

PHP code is not working inside HTML

As all have commented I have changed my code. Now the thing is when I am running my below php code as separate file its running like charm:

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


$conn = new mysqli($hostname, $username, $password, $database);

$sql = "SELECT username FROM users";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
echo "</select>";

?>


Like this: enter image description here

But when I am trying to include this into html code its not working:

<!DOCTYPE html>
<html>
<head>
<title>FusionCharts Column 2D Sample</title>
</head>
<body>
<div>
<?php
require("phpsqlajax_dbinfo.php");


$conn = new mysqli($hostname, $username, $password, $database);

$sql = "SELECT username FROM users";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
echo "</select>";

?>

</div>
<div id="chart-container">LOADING....</div>
<script src="js/jquery-2.2.4.js"></script>
<script src="js/fusioncharts.js"></script>
<script src="js/fusioncharts.charts.js"></script>
<script src="js/themes/fusioncharts.theme.zune.js"></script>
<script src="js/userChart.js"></script>
</body>
</html>


Its giving empty drop box:
enter image description here

Answer

Remove select inside select and don't mix mysqli_* with mysql_*.Do like below:-

<div>
   <select>
        <?php
        require("phpsqlajax_dbinfo.php");

        $conn = new mysqli($hostname, $username, $password, $database);

        if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
        }
        $query = "SELECT username FROM users";
        $result = $conn->query($query);

        ?>
        <?php
        while ($line = $result->fetch_assoc()) {
        ?>
        <option value="<?php echo $line['username'];?>"> <?php echo $line['username'];?> </option>

        <?php
        }
        ?>
    </select>

</div>

Note:-

file extension must be .php not .html.

Don't use (deprecated + removed) mysql_* library. Use mysqli_* or PDO