【问题标题】:Why am I getting duplicate items from MySQL query?为什么我从 MySQL 查询中得到重复的项目?
【发布时间】:2011-09-25 12:28:34
【问题描述】:

我正在使用对 PHP 文件的 Ajax 调用从 MySQL 数据库中获取数据并在 HTML 中填充选择选项。问题是选项中的重复项目,我不知道为什么。我在工作台中尝试了查询,它带回了我需要的东西。

PHP 文件:

<?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 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();
}

【问题讨论】:

    标签: php mysql sql ajax


    【解决方案1】:
    while($row = mysql_fetch_assoc($result))
    {
         $option .= "<option value=\"{$row[Material]}\">{$row[Material]}</option>";
    }
    echo $option;
    

    【讨论】:

    • 换句话说,在完成检索/构建数据之后进行输出。您的版本正在构建、输出、添加更多内容、再次输出等等......
    • 它不完全重复,你得到的东西类似于 1 12 123 1234 12345...
    • 我爱你。工作完美。 :-D
    【解决方案2】:

    您需要做的就是将echo $option; 移出while 循环,如下所示:

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

    您应该在构建后输出 HTML,而不是在构建时输出。

    【讨论】:

      【解决方案3】:

      使用mysql_fetch_assoc而不是mysql_fetch_array,因为数组以数字和名称两种格式返回值,所以它会加倍数据,

      其中mysql_fetch_assoc 返回数组作为数组的唯一名称元素..

      更多了解 试试

      <?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>";
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-24
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        • 1970-01-01
        • 1970-01-01
        • 2021-07-22
        • 1970-01-01
        相关资源
        最近更新 更多