Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

Fetching records from MySQL database with PHP to populate a drop down list

im having trouble with my code. I'm trying to populate a drop down list from my database but the list is showing empty space instead of database entries. I would be very grateful if anyone could help me.

<?php
include("db_config.php");
$sql="SELECT * FROM brojevi";
$result=mysqli_query($connection,$sql);
echo "<select name="id" size="1">";
echo "<option value="choose">-choose-</option>";
while($row=mysqli_fetch_array($result)){
unset($id,$broj);
$id=$row['id'];
$broj=$row['brojevi'];
echo "<option value="$id">$broj</option>";
}
echo "</select>";
?>

Here is the table( its a simple one cause im just making this for practice )

 CREATE TABLE `brojevi` (
 `id` int(11) NOT NULL auto_increment,
 `broj` int(11) NOT NULL,
 PRIMARY KEY  (`id`)
 );

INSERT INTO `brojevi` (`id`, `broj`) VALUES
(1, 1),
(2, 2);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are messing up your single and double quotes. Try this:

<?php
include("db_config.php");
$sql="SELECT * FROM brojevi";
$result=mysqli_query($connection,$sql);
echo '<select name="dropdown" size="1">';
echo '<option value="choose">-choose-</option>';
while($row=mysqli_fetch_array($result)){
    $id = $row['id'];
    $broj = $row['brojevi'];
    echo '<option value="' . $id . '">' . $broj . '</option>';
}
echo '</select>';
?>

When using html tags inside your echo, try to use single quotes for the echo and double quotes for html stuff like values,id's,classes etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...