Re: SQL Insert INTO question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Geekgirl,

Let me expand on the answers so far...

There are two things you can do here: add a new record or update an existing one. In SQL this makes a big difference and in your question you've confused the two (MySQL has a trick which kind of mixes the two and it is limited). I'm not exactly sure what you really intend to do so I'll show you are three and explain each:

A schema which might be like yours:

CREATE TABLE reviews
( review_id int NOT NULL auto_increment,
   review_txt text,
   primary key (review_id))

- To insert a new row
   INSERT INTO reviews (review_txt)
  	VALUES  ('$_POST[review]')

This will create a new record and will automatically generate the new review_id, if you want to specify the review_id you can do this
   INSERT INTO reviews (review_id , review_txt)
  	VALUES  ( $id, '$_POST[review]')

But this review_id must NOT exist or you will get a 'duplicate key' error.

-To update an existing row use this:
  UPDATE reviews
	 SET review_txt = '$_POST[review]'
  	WHERE review_id = $id

If the row with that review_id does not exist you will not get an error - but nothing will get saved; if the row with that review_id exists it will get updated.

-Finally there is a way to mix the two (I believe this is MySQL only):
   REPLACE INTO reviews (review_id , review_txt)
  	VALUES  ( $id, '$_POST[review]')

This works just like INSERT except if this review_id exists the old one will get deleted (this is because it is defined as the key in the create table statement). There is an important difference between this and the UPDATE statement; this is if you have other columns which are not mentioned in an UPDATE statement they will stay unchanged but REPLACE will delete the old row so all other columns will be their default values or NULL.

Feel free to write with more questions,

Good Luck,
Frank

On Dec 7, 2005, at 9:42 PM, geekgirl1 wrote:


This is the problem.  I want to add the value of $_POST[review] to the
reviews table where the unique id from the reviews table equals the
review id on my form.  The statement below does not work.  Should I
use UPDATE instead?

"INSERT INTO reviews (review_txt)
	VALUES
	('$_POST[review]') WHERE review_id = $id";

Marian


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux