如果有一行用户id,那么我想更新,如果没有插入(但是我被告知要使用replace)。表中有id(这是主键,auto inc)和用户id(index,session related to)。我有一个表单,当数据更改时,应该在数据库中为会话中的特定用户进行更改,否则它只是为会话中的特定用户添加

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 (thesis_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);
        }

有了这个页面就死定了。
编辑:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,

 PRIMARY KEY (`id`),
 KEY `user_id` (`user_id`)
 )

非常感谢

最佳答案

您不需要首先执行UPDATE操作-REPLACE即可为您处理所有这些操作。从MySQL manual开始:
REPLACE的工作方式与INSERT完全相同,只是如果表中的旧行与PRIMARY KEYUNIQUE索引的新行具有相同的值,则在插入新行之前删除旧行。见Section 13.2.5, “INSERT Syntax”
因此,只要idthesis表中的唯一键,您所需要的唯一SQL是:

REPLACE INTO thesis (id, thesis_Name, abstract)
VALUES ('$_SESSION[userid]', '$thesis_name', '$abstract');

10-01 05:11
查看更多