2012-04-28 44 views
0

我在使用下面的代码时,user_id没有被设置为唯一的,并且它使用相同的user_id输入了两次相同的数据。所以我把它设置为独特的,现在只是得到错误,查询失败。 所有帮助是极大的赞赏:(插入其他更新时添加重复行

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); 

    } 

我也曾尝试

$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)"; 
+0

尝试修改'模具()'语句,并给予一个唯一的消息为每个错误类型,看看那里的错误是提高 – 2012-04-28 12:16:07

+0

它插入查询 – user1296762 2012-04-28 12:18:41

回答

2

使用对重复密钥更新

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

例:

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) 

这基本上处理重复检查和选择MySQL和MySQL之间的所有插入和更新,这是快得多(约2倍)。作为奖励,VALUES()函数允许您从插入的行中检索值,以便您不必提供值两次,并且多行插入可以正常工作。

在响应编辑到OP:

您必须指定各列的UPDATE子句中改变。如果你想更新thesis_Name和abstract,那么你必须指定它们。如果您只指定导致更新的唯一密钥,那么它只会更新,而这很可能什么也不做!

+0

我用这一点,但它并不不断更新 – user1296762 2012-04-28 12:17:52

+0

你指定当您以前使用它时更新的值? – Brilliand 2012-04-28 12:21:39

+0

这现在只是刷新论文页面 – user1296762 2012-04-28 12:30:32