使用php从mysql获取html数据的下拉列表

deyfvvtc  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(390)

我有一个html下拉列表,其中的内容需要使用php从mysql数据库加载。
我试着像下面这样;但没有选择加载。

<strong> Select Data </strong> 
<select name="data1"> 
     <option value=""> NONE </option> 
<?php

$dd_res=mysql_query("Select relation FROM relation_names");
while($r=mysql_fetch_row($dd_res))
{ 
     echo "<option value='$r[0]'> $r[0] </option>";
}
?>
</select>

我也试过这样:

$q="SELECT DISTINCT *relation FROM relation_names";
$rs=mysql_query($q);
if($rs && mysql_num_rows($rs))
{
    while($rd=mysql_fetch_object($rs))
    { 
        echo("<option value='$rd->id'>$rd->name</option>");
    }
}

但我不知道为什么这些不起作用,请帮帮我。
我尝试了下面的代码作为评论。但期权名称并非空穴来风。

mwngjboj

mwngjboj1#

使用 mysqli_query() 代替 mysql_query() . 因为 mysql_query() 在php5.5.0中不推荐使用扩展,在php7.0.0中删除了扩展。

<strong> Select Data </strong> 
<select name="data1"> 
    <option value=""> NONE </option> 
<?php
    // Mysql db connection
    $con=mysqli_connect("localhost","my_user","my_password","my_db");

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    // Perform queries 
    $rs = mysqli_query($con,"SELECT DISTINCT relation FROM relation_names");
    if($rs && mysqli_num_rows($rs))
    {
         while($rd=mysqli_fetch_object($rs))
         { 
             echo("<option value='$rd->id'>$rd->name</option>");
         }
    }
    mysqli_close($con);
?>
</select>

请参阅下文 mysqli 延伸
mysqli\u connect()
mysqli\u connect\u errno()
mysqli\u connect\u error()
mysqli\u查询()
mysqli\u num\u rows()
mysqli\u fetch\u object()

gdrx4gfi

gdrx4gfi2#

<strong> Select Data </strong> 
<select name="data1"> 
<option value=""> NONE </option> 
<?php
// Mysql db connection
$con=mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Perform queries 
$rs = mysqli_query($con,"SELECT DISTINCT relation FROM relation_names");
if($rs && mysqli_num_rows($rs))
{
     while($rd=mysqli_fetch_object($rs))
     { 
         echo("<option value='$rd->id'>$rd->relation</option>");
     }
}
mysqli_close($con);
?>
</select>

相关问题