PHP自动填充<select>从数据库标记表单数据

时间:2018-07-14 08:52:08

标签: php sql mariadb

我不知道这是否是重复的问题。但是我只想知道如何用数据库中的数据自动填充

4 个答案:

答案 0 :(得分:1)

这是一个简单的foreach问题。

<?php
$con = mysqli_connect('localhost','root','user','password');
$sql = 'SELECT * FROM Users';
$result = mysqli_query($con,$sql);
$names = mysqli_fetch_all($result, MYSQLI_ASSOC);
$i = 0;
?>
<html>
 <body>
  <form>
   <select name="Names">
   <?php foreach($names as $name):?>
    <option value="<?php echo $i++; ?>"><?php echo $name['Names'];?></option>
   <?php endforeach;?>
   </select>
  </form>
 </body>
</html>

答案 1 :(得分:0)

##我在这里假设一个示例数据库##

<?php
 $servername = "localhost";
 $username = "root";
 $password = "";
 $dbname = "myDB";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT Names FROM Users";
$result = $conn->query($sql);
echo "<select name="Names">";
if ($result->num_rows > 0) {
// output data of each row
$i=1;
while($row = $result->fetch_assoc()) {
    echo "<option value=$i>".$row["Names"]."</option>";
$i++;
}
echo "</select>";
} 
$conn->close();
?> 

这是您可以执行的一种方法,您可以为此创建一个单独的函数。

答案 2 :(得分:0)

我不清楚您正在使用哪个数据库,因为您的问题尚不清楚。我试图让您知道它如何工作。

bow = df.Review2.str.split().apply(pd.Series.value_counts)
rating = df['Rating']
df_rating = pd.DataFrame([rating])
df_rating = df_rating.transpose()
bow = bow.join(df_rating)
bow.head()

答案 3 :(得分:0)

<?php
$db['db_host'] = 'localhost'; 
$db['db_user'] = 'root';
$db['db_pass'] = '';
$db['db_name'] = 'db';

foreach ($db as $key => $value) {
    define(strtoupper($key), $value);
}
$conn = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);

if(!$conn){
    die("Unable to connect");
}

$sql_query = "SELECT Names FROM Users";
$result = mysqli_query($conn,$sql_query);
echo "<select name="Names">";
if (mysqli_num_rows($result)> 0) {
$i=1;
while($row = mysqli_fetch_array($result) {
    echo "<option value=$i>".$row["Names"]."</option>";
    $i++;
}
echo "</select>";
} 
?>