user3473379 user3473379 - 7 months ago 223
PHP Question

Fetching data from MySQL database to html drop-down list

I search for answers here but haven't found a solution.
I have also added picture of the error.
I want the data to go to the first drop-down list ( above the error)
I think the method I try to perform is also create drop-down list, am I correct?



<form name="message" action="" method="post" onsubmit="" accept-charset="utf-8">
<div class="form-group">
<label id="senderName">שם השולח:</label>



</div>
<div class="form-group">

<label for="to_user">מען:</label>
<select name="to_user" class="form-control">
<option value="pick">בחר מהרשימה</option>
<?php

$sql = \mysqli_query("SELECT name From users");
$row = mysqli_num_rows($sql);


echo "<select name='to_user'>";
while ($row = mysqli_fetch_array($sql)){
echo "<option value='". $row['name'] ."'>" .$row['name'] ."</option>" ;
}
echo "</select>" ;

?>

</select>


</div>


picture of the error

Answer

In MySQLi, the first parameter of a query needs to be the database connection. Also, there's no need to add a \ before the statement.

$sql = \mysqli_query("SELECT name From users"); should be $sql = mysqli_query($con, "SELECT name From users");

Note: replace $con with your database connection variable!

As you mentioned that you wanted the result from the database to go inside the select form, simply adjust your code to look like this:

<select name="to_user" class="form-control">
<option value="pick">בחר מהרשימה</option>
<?php
$sql = mysqli_query($con, "SELECT name From users");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option value='". $row['name'] ."'>" .$row['name'] ."</option>" ;
}
?>
</select>