-1

I am working on a web app that allows a user to select from a series of drugs that are stored in a table. However, at the moment I can add the same drug multiple times. How do I prevent this from happening? I am not sure how to stop this.

Here is my code.

<h1>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Medication Appropriateness Index</h1>
        <div class="container-fluid">
        <div class="row">
             <div class="col-sm-12">
             <div class="well">
             <form class="form-horizontal" role="form" action="save_drug.php" method="post">
             <div class="form-group">
                  <label class="control-label col-sm-2">Drug:</label>
                  <div class="col-xs-3">
                  <select name="drug" id="Drug" class="form-control" required="">
                          <option value="" selected="" disabled="">Please select A drug...</option>
                          <?php
                          while($r1 = mysql_fetch_array($r_sel))
                          { ?>
                          <option value="<?php echo $r1['d_id']; ?>"><?php echo $r1['drug_name']; ?></option>
                          <?php
                          }
                         ?>
                          
                  </select>
                  </div>
             </div>
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Barry McDaid1982
  • 157
  • 1
  • 2
  • 14

1 Answers1

2

You can do something like that :

ALTER TABLE  `table_name` ADD UNIQUE ( `column_that_should_be_unique` )

Or you can check it in PHP using :

$query = mysqli_query($con, "SELECT * FROM table_name WHERE column_name='".$user_input."'");

if(mysqli_num_rows($query) > 0){
    //block user from inserting data
}

Or you can do both to ensure that the database will have no duplicates

  • Second example opens OP to sql injections. – chris85 Aug 02 '15 at 21:09
  • Thank you, can I ask how does that check to see if it is duplicated? – Barry McDaid1982 Aug 02 '15 at 21:10
  • Would I insert the php line before or inside the while statement? – Barry McDaid1982 Aug 02 '15 at 21:12
  • When you add a new drug, the query search your database to see how many drug with the name $user_input it has. If there is one or more then block the user from inserting a new drug. The best way is to prevent the user from ever inserting duplicate content when inserting new drugs instead of displaying only unique drugs. – GitCommit Victor B. Aug 02 '15 at 21:14
  • Or you can do like that : array_unique($r1['drug_name']) to remove duplicates from your array. See : http://php.net/manual/fr/function.array-unique.php – GitCommit Victor B. Aug 02 '15 at 21:16
  • Also use prepared statements don't use the SQL provided here. User input should never be inputted directly into SQL. http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – chris85 Aug 02 '15 at 21:16