1

For example, have a query like this:

<?php
$sql  = "INSERT INTO oppgave    
    (username, besvarelse, modulid) 
    VALUES
    ('$username', '$besvarelse', '$modulid');
    ";

    mysql_query($sql, $tilkobling);
?>

How can I do this:

If modulid row is not empty, echo "you have sent this modul before";

brasofilo
  • 25,496
  • 15
  • 91
  • 179
  • have you tried using triggers ? – daR Apr 29 '14 at 08:16
  • are you trying to check where that particular row already exists before inserting into the database? – user1978142 Apr 29 '14 at 08:18
  • to know if a field is empty or not refer to this link : http://stackoverflow.com/questions/8470813/how-do-i-check-if-a-column-is-empty-or-null-in-mysql – daR Apr 29 '14 at 08:21
  • the row modul id contain values from 1-6. if a user try input a value who alredy exist i want the user to get the message back that it already exist – user2879767 Apr 29 '14 at 08:21

2 Answers2

2

Try this:

<?php
$sql  = "INSERT INTO oppgave(username, besvarelse, modulid) 
         select '$username', '$besvarelse', '$modulid'
         from dual
         where not exists (select modulid from oppgave where modulid='$modulid')";

$result=mysql_query($sql, $tilkobling);
if(mysql_affected_rows()==0){
      echo "Failed to insert duplicate modulid";
}else{
      echo "inserted";
}
?>

In this SQL Query, it will allow insert only if $modulid isn't already exist in database table. Such situation you can also handle by applying UNIQUE constraint to table column (but remember, it allows NULL value at once)

Ravi Dhoriya ツ
  • 4,435
  • 8
  • 37
  • 48
1

Best way to do this, is by not allowing duplicates.
You can do this with your SQL QUERY.

Build your query by this:

 $sqlString ="INSERT INTO oppgave('" . $username . "', '" . $besvarelse . "', '" . $modulid . "')
    SELECT username, besvarelse, modulid
    FROM oppgave
    WHERE NOT EXISTS (SELECT *
                      FROM oppgave
                      WHERE modulid IS NULL)";

Please check all names and tablenames first ;)
Hope this helps.

If this the answer, please mark as answer.

Nick Prozee
  • 2,823
  • 4
  • 22
  • 49
  • But i think this isn't real answer to the question, as OP wants to *insert rows only if modulid isn't already exist in table* but here **your query won't allow duplicate rows (instead of just one column)**. Isn't it? – Ravi Dhoriya ツ Apr 29 '14 at 08:58