0

I have a sample database of students in a class with their id(UNIQUE), name,gender, birhdate, marks etc.

What i intend to do is :

  1. if the student has not entered his data, it should insert the data.
  2. if the student is using for the second time, the time should update. i used the code below but its not working .

Thanks!!

// open connection 
      $con = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); 
      // select database 
      mysql_select_db($db) or die ("Unable to select database!");
      mysql_query("INSERT INTO UserData VALUES ('$id','$name','$gender','$email','$birthday','Marks','NOW()')");
      mysql_close($con);
1
  • "if the student has not entered his data, it should insert the data." What do you mean by that?`How to insert data which is not known? Commented Mar 29, 2011 at 1:41

4 Answers 4

1

I will strongly suggest that you use the field names in the query:

INSERT INTO UserData (`id`, `name`, `gender`, `email`, `bday`, `marks`, `time`)
VALUES ('$id','$name','$gender','$email','$birthday', $marks, NOW())
ON DUPLICATE KEY UPDATE `time` = NOW()

I am assuming that you have a unique index on id (or it is the primary key). Also, please replace the column names in the query above with the actual column names as per your schema.

For more details, see this.

If you can post your table schema, then I can provide the exact query that you need to use.

Sign up to request clarification or add additional context in comments.

2 Comments

Never seen this- pretty cool. I have doubts that updating the time is really all they want to do.
Yeah, updating just the time does not make much sense. Anyway, the query can be extended to update multiple columns. Also, if all columns need to be updated, then REPLACE can be used instead of INSERT in his original query.
0

I recommend using an ORM like Propel which allows you to write code like this:

$user = UserQuery::create()->findPK($id);
if(!$user) {
  $user = new User();
  $user->setId($id);
}
$user->setName($name);
$user->setGender($gender);
$user->setEmail($email);
$user->save();

Comments

0

remove the quotes enclosing NOW() so instead of 'NOW()' it should be just NOW(), as it is a MYSQL function

Comments

0

INSERT != UPDATE

If you want to update an existing record you need to write an UPDATE query. You could use a REPLACE query, but it will overwrite the entire row.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.