PHP PDO简单插入或更新功能 [英] PHP PDO simple insert or update function

查看:62
本文介绍了PHP PDO简单插入或更新功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试创建一个简单的PHP PDO更新函数时,如果找不到该字段将插入该字段,我创建了这个小片段.

In trying to create a simple PHP PDO update function that if the field is not found would insert it, I created this little snippet.

function updateorcreate($table,$name,$value){
    global $sodb;
    $pro = $sodb->prepare("UPDATE `$table` SET value = :value WHERE field = :name");
    if(!$pro){
        $pro = $sodb->prepare("INSERT INTO `$table` (field,value) VALUES (:name,:value)");
    }
    $pro->execute(array(':name'=>$name,':value'=>$value));
}

它无法检测到更新功能是否可以与if(!$pro);一起使用.我们如何使这一功能起作用.

It does not detect though if the update function is going to work with if(!$pro); How would we make this one work.

推荐答案

您正在将$pro分配给prepare,而不是execute语句.

You are assigning $pro to the prepare, not the execute statement.

话虽如此,如果您使用的是mysql,则可以使用insert... on duplicate key update语法.

Having said that, if you are using mysql you can use the insert... on duplicate key update syntax.

insert into $table (field, value) values (:name, :value) on duplicate key update value=:value2

您不能两次使用相同的绑定参数,但是可以将两个绑定参数设置为相同的值.

You can't use the same bound param twice, but you can set two bound params to the same value.

此mysql语法仅在存在键(主键或另一个唯一键)的情况下 起作用,并且会导致插入失败.

This mysql syntax will only work where a key (primary or another unique) is present and would cause an insert to fail.

这篇关于PHP PDO简单插入或更新功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆