php mysql 插入记录,php – 独特的记录mysql插入

mysql页:

The main idea is to insert records using the ignore statement. If

you use the IGNORE keyword, errors that occur while executing the

INSERT statement are treated as warnings instead. For example, without

IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY

value in the table causes a duplicate-key error and the statement is

aborted. With IGNORE, the row still is not inserted, but no error is

issued. Then retrieve the last ID using mysql_insert_id

如果记录不存在,它将被插入并返回最后一个ID.

现在,如果没有记录返回,可以进行选择.这意味着一条记录已经存在,所以只需使用它.

例:

// make sure $id is safe (preventing sql injections)

$sql = "INSERT IGNORE INTO yourtable SET `field1` = 'value1' ... ";

mysql_query($sql);

if(mysql_affected_rows() == 1) { // no record found and then the inserts worked

$id = mysql_insert_id(); // id from the primary key

// add to cache

}

else {

// you can also cache them when they were inserted (faster to run than a select statement)

$id = retreiveFromCache($field1, $field2 /* etc...*/);

if(!$id) { // no record found in cache

// now the select can be done using the fields received

// make sure your use the right index otherwise it can be slow

$sql = "SELECT id FROM promotions_referrals WHERE `field1` = 'value1' ... "; //

$query = mysql_query($sql);

$row = mysql_fetch_assoc($query);

$id = $row['id'];

// add to cache

}

}

在这一点上,您将有$id分配,您确定没有重复/ mysql错误.

注意:如果域属于一个客户端,请使用客户端标识,而不是使用域.这样,您将使用INT作为比VARCHAR快的索引.相同的推荐代码.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值