简体   繁体   English

PHP / MySQL检查值是否存在,如果不插入它

[英]PHP/MySQL Check If Value Exists, If So-Do Not Insert It

I asked that before, but couldn't figure it out. 我之前曾问过,但无法弄清楚。

I have this form: 我有这个表格:

<?php
if ( isset ($_REQUEST['fname']{0}, $_REQUEST['lname']{0}, $_REQUEST['mail']{0}, $_REQUEST['url']{0}) ){
   $query = "INSERT INTO table1 (url, fname, lname, mail) VALUES ('".$_REQUEST[url]."', '".$_REQUEST[fname]."', '".$_REQUEST[lname]."', '".$_REQUEST[mail]."')"; 
$result = mysql_query($query)
or die ("Query Failed: " . mysql_error());
}
else{
   echo "One Of The Values Not Entered Correctly. Please Press Back In Your Browser And Enter The Missing Values.";
}
?>

And I would like to know if it is possible for it to check if a url exists in the system before entering it again. 我想知道是否有可能在再次输入之前检查系统中是否存在网址。

Check out MySQL INSERT ... ON DUPLICATE KEY UPDATE , which you can use if you set the URL as unique in your database. 检出MySQL INSERT ... ON DUPLICATE KEY UPDATE ,如果您在数据库中将URL设置为唯一,则可以使用它。

Also, you should make sure to sanitize your inputs before inserting them: http://php.net/manual/en/function.mysql-real-escape-string.php 另外,在插入输入之前,请务必清除输入内容: http : //php.net/manual/zh/function.mysql-real-escape-string.php

Replace does exactly what you need. 替换功能完全满足您的需求。

http://dev.mysql.com/doc/refman/5.0/en/replace.html http://dev.mysql.com/doc/refman/5.0/en/replace.html

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted REPLACE的工作方式与INSERT完全相同,不同之处在于,如果表中的旧行与PRIMARY KEY或UNIQUE索引的新行具有相同的值,则在插入新行之前删除该旧行

Make sure the url column in db is PRIMARY or UNIQUE. 确保db中的url列为PRIMARY或UNIQUE。

ALTER TABLE  `table1` ADD PRIMARY KEY(`url`);

Before you can use this insert function, you must add mysql_connect(), mysql_select_db() 在使用此插入函数之前,必须添加mysql_connect(),mysql_select_db()

function insert($post = array(), $tb, $announce=true, $ignore="",$updateonduplicate=false){

        foreach($post as $k => $v){
            $fields[$k] = $v;
            $values[] = mysql_real_escape_string($v);
        }

        $query = "INSERT {$ignore} INTO `{$tb}` (`".implode("`,`",array_keys($fields))."`)"." VALUES ('".implode("','",$values)."')";

        if($updateonduplicate !== false){

        $query .= " ON DUPLICATE KEY UPDATE ";
        $countfields = 0;
         foreach($fields as $field => $value){

            $query .= " `".$field."`='".$value."'";

            $countfields++;
            if(count($fields) !== $countfields)
            $query .= ",";
         }
        }


//mysql_connect(), mysql_select_db()
// assuming db is connected, database selected
            $result = mysql_query($query)

        if($announce !== true)
        return;


        if(!$result){       
            $announce = "Query Failed: " . mysql_error();

        }else{
            $announce = "insert_success";

        }

        if($updateonduplicate === true && $result === 0 && mysql_affected_rows() >=1){
            $announce = "update_success";
        }   

        return $announce;
    }

$post = array();
$post['url'] = $_REQUEST[url];
$post['fname'] = $_REQUEST[fname];
$post['lname'] = $_REQUEST[lname];
$post['mail'] = $_REQUEST[mail];

insert($post,"table1",true,"",true);

If you do have a UNIQUE or PRIMARY KEY index on the url column, INSERT IGNORE will do what you want. 如果您确实在url列上具有UNIQUEPRIMARY KEY索引,则INSERT IGNORE将做您想要的。 New rows will go in and duplicates will be ignored. 新行将进入,重复项将被忽略。 INSERT ... ON DUPLICATE KEY UPDATE will allow you to update if there's a duplicate, if that's what you want to do. INSERT ... ON DUPLICATE KEY UPDATE将允许您更新是否有重复项(如果您要这样做)。 Also, pay good attention to the SQL injection comments from the others here. 另外,请注意此处其他人的SQL注入注释。

Given the description in the OP and subsequent comments (try insert, throw error if exists), I'd simply make sure the required "unique" columns had unique constraints or were part of the primary key. 给定OP中的描述和后续注释(尝试插入,如果存在则抛出错误),我只要确保所需的“唯一”列具有唯一约束或属于主键即可。

Then, simply attempt the insert and catch / handle any unique constraint violation errors. 然后,只需尝试插入并捕获/处理任何唯一的违反约束的错误。 This is quicker than checking for existing records. 这比检查现有记录更快。

Using PDO with the error mode set to throw exceptions means you can wrap this code nicely in a try catch block. 在错误模式设置为引发异常的情况下使用PDO意味着您可以将此代码很好地包装在try catch块中。 From memory, unique constraint violations set the exception code to something you can test against. 从内存中,唯一的约束违例会将异常代码设置为可以测试的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM