user1296762
user1296762

Reputation: 512

Insert else update

I want the form to update if their is a row for the particular user_ID but insert if not. I have tried with insert... on duplicate key update but failing miserably so this is my next attempt. user_ID is not an unique index but 'ID' in my table is and is an auto increment field. User_ID is just an index that the session is based around. This is the code I have been using now:

if (empty($err)) {

        $thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
        $abstract = mysql_real_escape_string($_POST['abstract']);


$query="UPDATE thesis SET (`thesis_Name`='$thesis_Name',
`abstract`='$abstract') WHERE id='$_SESSION[user_id]'
IF ROW_COUNT()=0
REPLACE INTO  thesis (theis_Name,abstract)VALUES ('$thesis_Name', '$abstract')
";

mysql_query($query) or die();
// query is ok?

if (mysql_query($the_query, $link) ){

 // redirect to user profile
   header('Location: myaccount.php?id=' . $user_id);
   }

At the moment when pressing submit, I get a blank page.

Upvotes: 0

Views: 124

Answers (3)

Sérgio Carvalho
Sérgio Carvalho

Reputation: 1143

REPLACE INTO is the answer. If you still wish to use your code, you are missing a semicolon in your query:

$query="UPDATE thesis SET (`thesis_Name`='$thesis_Name',
`abstract`='$abstract') WHERE id='$_SESSION[user_id]';
IF ROW_COUNT()=0
INSERT INTO  thesis (theis_Name,abstract)VALUES ($thesis_Name, $abstract)
";

Upvotes: 0

Halcyon
Halcyon

Reputation: 57729

REPLACE is what you want. You will need to define a UNIQUE KEY on id (if it's not a PRIMARY KEY which is unique be definition).

Upvotes: 0

GDP
GDP

Reputation: 8178

Have you tried "REPLACE INTO..." instead of "INSERT INTO..."

Upvotes: 2

Related Questions