如何使用php中的函数从db获取名称列表
问题描述:
This is my code to get name list from the database but I am not able to get values where is the error can anyone pls help me
// database connection where php is my database name
<?php
$con=mysql_connect("localhost","root","root");
mysql_select_db("php",$con);
?>
// html body for getting value in option
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<select name="select" >
<option>Select College From Here</option>
<?php $getoptions = get_name(); ?>
<?php foreach ($getoptions as $key => $value) { ?>
<option><?= $value ?></option>
<?php } ?>
</select>
<input type="submit" name="sub">
</form>
// function to get name list from the database is this query right or wong ??
<?php
function get_name(){
$option=array();
$query="select * From login ";
$result=mysql_query($query);
while($row=mysql_fetch_array($result)){
$option [$row->id] = strtoupper($row->name);
}
$option;
}
?>
Help me regarding this that function not returning me the name from the table and m not able to see the list on select box.. and tell me how can i see the what function is going to return how to get function return value, can i alert the return value or echo the value
这是我从数据库中获取名单的代码,但是我无法获取值到哪里 错误任何人都可以帮助我
//数据库连接,其中php是我的数据库名称
&lt;?php
$ con = mysql_connect(“localhost”,“root”,“root”);
mysql_select_db(“ php“,$ con);
?&gt;
//用于获取选项中的值的主体
&lt;!DOCTYPE html&gt;
&lt; html&gt;
&lt; head&gt;
&lt; title&gt; &lt; / title&gt;
&lt; / head&gt;
&lt; body&gt;
&lt; form method =“post”&gt;
&lt; select name =“select”&gt;
&lt; option&gt;从此处选择College&lt; / 选项&gt;
&lt;?php $ getoptions = get_name(); ?&gt;
&lt;?php foreach($ getoptions as $ key =&gt; $ value){?&gt;
&lt; option&gt;&lt;?= $ value?&gt;&lt; / option&gt;
&lt; ?php}?&gt;
&lt; / select&gt;
&lt; input type =“submit”name =“sub”&gt;
&lt; / form&gt;
//用于从数据库中获取名称列表的函数 这个查询是正确的还是wong ??
&lt;?php
function get_name(){
$ option = array();
$ query =“select * From login”;
$ result = mysql_query($ query) ;
while($ row = mysql_fetch_array($ result)){
$ option [$ row-&gt; id] = strtoupper($ row-&gt; name);
}
$ option;
} \ n?&gt;
code> pre>
请帮我解释一下这个函数没有从表中返回我的名字而且我无法在选择框中看到列表..并告诉我 我如何才能看到函数将返回如何获取函数返回值,
我可以提醒返回值或回显值 p>
div>
答
try this but not tested
function get_name()
{
// your code
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$option [$id] = strtoupper($row['name']);
}
return $option;
}
check this for test
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
echo $id . "==" . $row['name'];
echo "<br>";
$option [$id] = strtoupper($row['name']);
}
$option;
print_r($option);
答
should replace this
while($row=mysql_fetch_array($result)){
$option [$row->id] = strtoupper($row->name);
}
$option;
by this code
while($row=mysql_fetch_array($result)){
$option [$row['id']] = strtoupper($row['name']);
}
return $option;