views:

44

answers:

3

dear all. i have a form that consist of two textfield and one combobox. i want prevent the duplicate entry data from client side. i get combobox data from DB, like:

<select id="line" name="faline" >
<?php
   $sql="SELECT `Line_Name` FROM `prod_sch` WHERE `Line_Name` LIKE 'FA %' GROUP BY `Line_Name` ORDER BY `Line_Name`";
   if ($sql) {
               $res=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
              }
   while ($dat = mysql_fetch_array($res, MYSQL_NUM)) {
           echo "\t\t\t\t\t\t\t\t<option value='".$dat[0]."'>".$dat[0]."</option>\n";
         }
?>
</select>

how to combine or modify this code:

<script language="javascript" type="text/javascript">
    $(function() {
        $("#Button1").click(function(e) {
            var itemExists = false;
            var txt = $("#Text1").val();
            e.preventDefault();
            $("#Select1 option").each(function() {
                if ($(this).text() == $.trim(txt)) {
                    itemExists = true;
                    alert('Item already exists');
                }
            });

          if (!itemExists) {
          $("#Select1").append("<option value=\"1\">" + txt + "</option>");
          $("#Text1").val('');
          }
        });
    });           
</script>   
+1  A: 

First, build an array with the Line_Names:

<select id="line" name="faline" >
<?php
   $sql="SELECT `Line_Name` FROM `prod_sch` WHERE `Line_Name` LIKE 'FA %' GROUP BY `Line_Name` ORDER BY `Line_Name`";
   if ($sql) {
               $res=mysql_query($sql) or _doError(_ERROR30 . ' (<small>' . htmlspecialchars($sql) . '</small>): ' . mysql_error() );
              }

   $lineNames = array();
   while ($dat = mysql_fetch_array($res, MYSQL_NUM)) {
           $lineNames[] = $dat[0];
         }

Then call array_unique:

   $lineNames = array_unique($lineNames);

And finally iterate once again:

   foreach ($lineNames as $lineName) {
           echo "\t\t\t\t\t\t\t\t<option value='".$lineName."'>".$lineName."</option>\n";
           }
?>
</select>
strager
@strager, I believe that my answer is more efficient, not to mention that it's less code :)
Jacob Relkin
I agree with jacob. Let the database do the work.
Matt H
This looked like a PHP question to me, not a SQL one.
strager
@all:please check again my question..i have changed it.
klox
+2  A: 

I believe that using SELECT DISTINCT will do the trick.

Jacob Relkin
A: 

Can't you just use SQL to do this for you? i.e. by using the distinct keyword

$sql="SELECT distinct `Line_Name` FROM `prod_sch` WHERE `Line_Name` LIKE 'FA %' GROUP BY `Line_Name` ORDER BY `Line_Name`";

Sorry I had unique there before I meant distinct.

Matt H
I thought UNIQUE was an indexing constraint. Can it really be used like this?
strager
i have change my question..for getting combobox data there is no problem.
klox