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

时间:2018-05-28 14:31:56

标签: php mysql sql

在插入或更新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);

    }

2 个答案:

答案 0 :(得分:2)

通常使用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 _”的另一个原因。

答案 1 :(得分:0)

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

这样,您可以处理具有NULL值的唯一键