我想为DB中的选择员工姓名创建一个自动完整文本框。但它会导致查询错误
Warning: mysql_fetch_array() expects parameter 1 to be resource, string given in
以下是我的代码。
<?php
include 'func/db_connect.php';
if(!empty($_POST["keyword"])) {
$query ="SELECT * FROM employee WHERE name like '" . $_POST["keyword"] . "%' ORDER BY name LIMIT 0,6";
$result=mysql_fetch_array($query);
if(!empty($result)) {
?>
<ul id="name-list">
<?php
foreach($result as $name) {
?>
<li onClick="selectName('<?php echo $name["name"]; ?>');"><?php echo $name["name"]; ?></li>
<?php } ?>
</ul>
<?php } } ?>
此代码有什么问题,任何人都可以帮助我!
答案 0 :(得分:3)
试试这个
Date
将$result=mysql_query($query);
while($data = mysql_fetch_assoc($result))
{
$row[] = $data;
}
更改为!empty($result)
答案 1 :(得分:2)
试试这个,您需要使用mysql_query()
函数并将字符串直接传递给 mysql_fetch_array()
$query = mysql_query("SELECT * FROM employee WHERE name like '" . $_POST["keyword"] . "%' ORDER BY name LIMIT 0,6");
$result = mysql_fetch_array($query);
注意:在PHP 7.x中弃用并删除了mysql_ *函数。使用MySQLi或PDO_MySQL扩展
答案 2 :(得分:2)
您需要实际执行查询才能获取结果:
$result = mysql_query("SELECT id, name FROM mytable");
$rows = mysql_fetch_array($result);
查看PHP文档以获取更深入的示例: http://php.net/manual/de/function.mysql-fetch-array.php
旁注:使用mysql_ *函数已被弃用了一段时间,请查看mysqli!
答案 3 :(得分:1)
您已先执行查询
PHP 5.5.x中不推荐使用的功能
现在不推荐使用原始MySQL扩展,并且在连接到数据库时会生成E_DEPRECATED错误。而是使用 MYSQLi或PDO_MySQL扩展。
<?php
// include 'func/db_connect.php';
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
if(!empty($_POST["keyword"])) {
$name_val = '%'.$_POST["keyword"].'%';
$stmt = $conn->prepare("SELECT * FROM employee WHERE name like ? ORDER BY name LIMIT 0,6");
$stmt->bind_param('s',$name_val);
$qry_res=$stmt->execute();
if($row_count>0) {
?>
<ul id="name-list">
<?php
while($row = $qry_res->fetch_assoc())
{
?>
<li onClick="selectName('<?php echo $row["name"]; ?>');"><?php echo $row["name"]; ?></li>
<?php } ?>
</ul>
$stmt->close();
答案 4 :(得分:0)
你可以试试这个:
$cn=mysql_connect("localhost","root","");
if(!$cn)
{
echo "Unable to connect";
die();
}
$query = "Select * from table";
$result= mysql_query($query,$cn);
$n = mysql_num_rows($result);
if($n>0)
{
while($rw=mysql_fetch_array($result))
{
$owenername=$rw["owenername"];?>
<p>Owner Name:<?php echo $owenername;?> </p>
<?php}
}
else
{
?>data not found
<?PHP
}
?>