如果存在则更新一行,如果没有创建一个新的MySQL

mda*_*nce 7 php mysql

我正在将数据库中的名称,编号和公司插入.

我的表很简单:

id(primary key)
name
slideView
company
Run Code Online (Sandbox Code Playgroud)

如果传递给它的名称存在,我需要更新此信息,如果没有创建包含此数据的新行.我看过了,REPLACE INTO但我不认为这对我有用......因为我根本不接触ID.

我的代码是:

insertData($name,$count,$company);

function insertData($name, $count, $company) {

    #Try/Catch statement to connect to DB, and insert data
    try {
        #DB username/password   
        $usernameDB = '****';
        $passwordDB = '****';

        #Create new PHP Database Object with the address, username, and password as parameters
        $pdo = new PDO('mysql:host=localhost;dbname=*****', $usernameDB, $passwordDB);

        #Set pdo attributes to handle errors 
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        #assign the sth variable (sth means statement handle) to insert the data
        $sth = $pdo->prepare("REPLACE INTO ***** SET name = ?, slideView = ?, company = ?");

        #Execute the insert
        $sth->execute(array($name,$count,$company));

    #Error if can't connect or insert
    } catch(PDOException $e) {
        echo 'Error: ' . $e->getMessage();
    }#/try
}
Run Code Online (Sandbox Code Playgroud)

我是SQL的新手,并且havnt找到了一个很好的方法来做到这一点.

Flu*_*feh 5

您可能最好使用insert ... on duplicate update这种语法,尽管这意味着传递一些额外的参数,但它可以消除替换为语法中似乎不断出现的某些问题。

REPLACE INTO ***** SET name = ?, slideView = ?, company = ?
Run Code Online (Sandbox Code Playgroud)

可以写成:

insert into yourTableName (name, slideView, company)
    values (:name, :slideView, :company)
    on duplicate key update set
        slideView=:$slideView2, company=:company2
Run Code Online (Sandbox Code Playgroud)

然后执行是这样的:

$sth->execute(array(':name' => $name, ':slideView' => $count,
    ':company' => $company, ':slideView2' => $count, ':company2' => $company));
Run Code Online (Sandbox Code Playgroud)

上面的格式使用命名参数(它们更容易读取/调试),并将在数据库中插入一个新行 - 或者如果唯一/主键列已经name具有该值,则使用该值的其余部分更新该行信息。

您必须在此处使用参数两次(即使幻灯片视图和公司将包含相同的信息),因为没有参数可以在查询中使用两次。


cin*_*ada 2

REPLACE INTO 应该可以正常工作 - 它还检查具有 UNIQUE 约束的列。因此,您只需将列标记name为唯一,以便 REPLACE INTO 会将其识别为重复。

我还没有尝试过这个特定的用例,但文档似乎允许这样做。