开发者

Why am I getting duplicate items from MySQL query?

开发者 https://www.devze.com 2023-03-16 13:24 出处:网络
I am using an Ajax call to a PHP file to 开发者_如何学Pythonget data from MySQL database and populate select options in HTML. The problem is that duplicate items in the options and I don\'t know why.

I am using an Ajax call to a PHP file to 开发者_如何学Pythonget data from MySQL database and populate select options in HTML. The problem is that duplicate items in the options and I don't know why. I tried the query in workbench and it brings back what I need.

PHP file:

<?php
    $q=$_GET["q"];

   // open db connection code

   $query = "select * from r2rtool.materialtype where type = 'FE' and tools like '%".$q."%'";
   $result = mysql_query($query);

   $option = "";

   while($row = mysql_fetch_array($result))
    {
        $mat = $row["Material"];
        $option.="<option value=\"$mat\">".$mat."</option>";

        echo $option;
    }

   // close db connection
?>

Ajax function:

function populatematerial(str)
{
    if (str=="") {
      document.getElementById("txtHint").innerHTML="";
      return;
    }

    if (window.XMLHttpRequest) {
      // IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }

    else{
      // IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
      }
    }

    xmlhttp.open("GET","phpfile.php?q="+str,true);
    xmlhttp.send();
}


while($row = mysql_fetch_assoc($result))
{
     $option .= "<option value=\"{$row[Material]}\">{$row[Material]}</option>";
}
echo $option;


All you need to do is to move the echo $option; out of the while loop, like so:

while($row = mysql_fetch_array($result))
{
    $mat = $row["Material"];
    $option.="<option value=\"$mat\">".$mat."</option>";
}
echo $option;

You should output the HTML after you built it, not while you build it.


use mysql_fetch_assoc instead of mysql_fetch_array because array returns value in numbers and name both format, so it will twice data,

where mysql_fetch_assoc returns array as only name element of array ..

for more understanding try

<?php 
$query = mysql_query("some query ");
$row = mysql_fetch_array($row);
$assoc = mysql_fetch_array($row);
print_r ($row);
echo "<br>";
print_r ($assoc);
echo "<br>";
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消