选择从数据库中读取的选项菜单并使用它的值

时间:2013-09-23 07:18:50

标签: php mysql

<?php
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("tnews2") or die(mysql_error());

$query = "SELECT name,id FROM categories ORDER BY ID DESC LIMIT  0,6";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");?>

    <select name="categories">
<?php while ($row = mysql_fetch_array($result)){
?>
   <option value=" <?php $row['path']; ?> ">
     <?php echo $row['name']; ?>
    </option>
<?php
}
?>        
</select>?>

所以这是选择选项菜单,它是我从数据库中读取的值,但是当我尝试获取所选值时,我只得到第一个。

<?php
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("tnews2") or die(mysql_error());


   if(!empty($_POST['title']) && !empty($_POST['date']) && !empty($_POST['txt']) && !empty($_POST['image'])){
$TITLE=$_POST['title'];
$DATE=$_POST['date'];
$TXT=$_POST['txt'];
$IMAGE=$_POST['image'];
$CATEGORIES=$_POST['categories'];
echo $CATEGORIES;
$ANSWER=$_POST['main'];
$MAINPAGE=0;

你能否帮助我想出选择的选项

3 个答案:

答案 0 :(得分:7)

编辑:(缩减代码)

<?php
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("tnews2") or die(mysql_error());

$query = "SELECT name,id,path FROM categories ORDER BY ID DESC LIMIT  0,6";
$result = mysql_query($query) or die(mysql_error()."[".$query."]");
?>

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

答案 1 :(得分:1)

我更喜欢使用mysqli

这样做
<?php
/* Database connection settings */
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'tnews2';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

/* Your query */
$result = $mysqli->query("SELECT name,id,path FROM categories ORDER BY ID DESC LIMIT  0,6";) or die($mysqli->error);
?>

然后将元素添加到html中:

<select name="categories">
    <option value="Select School">Select Shool</option>
    <?php
    while ($row = mysqli_fetch_array($result)) {
        echo "<option value='" . $row['path'] . "'>'" . $row['name'] . "'</option>";
    }
    ?>        
</select>

答案 2 :(得分:-1)

我建议您确保在SQL查询中订购字段以匹配您希望它们的顺序,然后使用:

$query = "SELECT path, name, id FROM categories ORDER BY ID DESC LIMIT  0,6";

echo "<option value='".$row[0]."'>'".$row[1]."'</option>";

您的代码将作为“代码片段”更加可重用,您需要做的就是编写一个新的SQL查询