I was using the code below, when user_id wasnt set as unique and it entered the same data twice with the same user_id. So I have set it to unique and now just get Error, query failed.
All help is greatly appreciated 🙁
if (empty($err)) {
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
// insert into the database
$the_query ="SELECT * FROM thesis WHERE user_id='$_SESSION[user_id]'";
$testResult = mysql_query($the_query) or die('Error, query failed');
if(mysql_fetch_array($testResult) == NULL){
//insert...
$the_query ="INSERT INTO thesis (`user_id`,`thesis_Name`,`abstract`)
VALUES ($user_id, $thesis_Name, $abstract)";
$result = mysql_query($the_query) or die('Error, query failed') ;
}
else{
//update...
$the_query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE user_id='$_SESSION[user_id]'";
$result = mysql_query($the_query)or die('Error, query failed');
}
// query is ok?
if (mysql_query($the_query, $link) ){
// redirect to user profile
header('Location: myaccount.php?id=' . $user_id);
}
I have also tried
$the_query = "INSERT INTO thesis (`user_id`,`thesis_Name`,`abstract`)
VALUES ($user_id, $thesis_Name, $abstract)
ON DUPLICATE KEY UPDATE thesis_Name=VALUES(thesis_Name), abstract=VALUES(abstract)";
Use ON DUPLICATE KEY UPDATE.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Example:
This basically handles the duplicate checking and choosing between INSERT and UPDATE all on the MySQL side, which is much faster (by about a factor of 2). As a bonus, the VALUES() function allows you to retrieve values from the row being inserted, so that you don’t have to provide the values twice and multi-row inserts work properly.
In response to an edit to the OP:
You have to specify the individual columns to change in the UPDATE clause. If you want to update thesis_Name and abstract, then you have to specify those. If you specify only the unique key that caused the update in the first place, then it will update only that, which will most likely do nothing!