我想检查之前插入或更新mysql

zbq4xfa0  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(277)

在插入或更新mysql之前检查我的代码不工作我不知道为什么

$sql = "SELECT * FROM downloads WHERE name = '" . $details['name']."' " ;
    $result = mysql_query($sql);

if( mysql_num_rows($result) === 0) {
    $sql = "INSERT INTO downloads (name, idu) VALUES ('".$details['name']."', '".$details['idu']."')";
    $result = mysql_query($sql);
   }
else{

    $sql2 = "UPDATE downloads SET idu='".$details['idu']."' WHERE name='". $details['name'] ."'";
    $result = mysql_query($sql2);

    }
mccptt67

mccptt671#

`INSERT INTO xxxxxxx
(dd1, dd2, dd3, dd4, dd5, dd6, dd7, dd8, dd9, dd0)
select 'config', '9', NULL, 'appname', '2016-10-20 11:55:01', NULL, 'xxx', '2007-09-18 16:31:03', NULL, NULL
FROM dual 
Where not exists (select * from xxx where dd2 = '9' and dd4 = 'appname' and
dd6 is NULL and  dd0 is NULL) ;`
`UPDATE xxx
SET 
dd1 = 'config', dd2 = '9', dd3 = NULL, dd4 = 'appname', dd5 = '2016-10-20 11:55:01',
dd6 = NULL, dd7 = 'xxx', dd8 = '2007-09-18 16:31:03', dd9 = NULL, dd0 = NULL
Where 
dd2 = '9' and dd4 = 'appname' and
dd6 is NULL and  dd0 is NULL;`

这样就可以处理具有空值的唯一键

roejwanj

roejwanj2#

通常使用 on duplicate key update :

INSERT INTO downloads (name, idu)
    VALUES (?, ?)
    ON DUPLICATE KEY UPDATE idu = VALUES(idu);

要想让它起作用,你需要 name 待申报 unique 或者有一个 unique 索引:

ALTER TABLE downloads ADD CONSTRAINT unq_downloads_name UNIQUE (name);

这个 ? 是参数的占位符。不要用参数值咀嚼查询字符串!这样做会使查询更难优化、调试,并使其容易受到sql注入攻击。不管是好是坏,不再支持的“mysql\”函数不支持参数,所以这是更新代码(和技能)的另一个原因到“mysqli”。

相关问题