使用SQL数据的动态选择列表

b91juud3  于 2022-09-18  发布在  Java
关注(0)|答案(4)|浏览(200)

I am trying to create a select drop-down list using php. Every time i try, i get an error. Here is my code:

The function:

function dropDown(){
    $options="<select>"; 
    $connect = mysql_connect('localhost','id','pass') or die ("couldn't   connect!").mysql_error; 

    mysql_select_db('db') or die('could not connect to database!');

    $sql="SELECT * FROM DESC"; 
    $result=mysql_query($sql); 

    while ($row=mysql_fetch_array($result)) { // this is line 60
        $name=$row["name"]; 

        $options.="<option value=\"$name\">".$name."</option>"; 
    } 

    $options.= "</SELECT>";
    return "$options";
}

and then i just call it in my code

<?php  
include ('includes/functions.php');

// ...

$list = dropDown();
echo "$list";

// ...

?>

The error I get is:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/garagenj/public_html/dispatch/includes/functions.php on line 60
ippsafx7

ippsafx71#

If your table name isDESC then that's your problem. It's all about namespacing. You can't even have a field named desc, I've tried. It errors everytime

6yjfywim

6yjfywim2#

Either your table is using a reserved word (desc) or your query is all jacked up. Try this:

select * from table order by col desc

Be sure to replace table and col with your table name and column name.

jmo0nnb3

jmo0nnb33#

SELECT * FROM DESC ??????

  • From what table
  • Or, if the table name is DESC. escape them with ticks

And You dont have start a new connection, every time you call the function. Put your connection part somewhere else

$connect = mysql_connect('localhost','id','pass') or die ("couldn't   connect!").mysql_error; 
mysql_select_db('db') or die('could not connect to database!');

function dropDown(){
    $options="<select>"; 
    $sql="SELECT * FROM `DESC`"; 
    $result=mysql_query($sql); 

    while ($row=mysql_fetch_array($result)) { 

        $name=$row["name"]; 

        $options.="<option value=\"$name\">".$name."</option>"; 
    } 

    $options.= "</SELECT>";
    return $options;

}
v64noz0r

v64noz0r4#

This is wrong:

$sql="SELECT * FROM DESC";

You forgot to add the table name to select from

相关问题