开发者

How do I insert data while updating?

when updating a database having 4 tables, if a particular table hasn't got the data which is updating..then how can I insert the same to that table??

my database is based on SEO so inserting web information to all 4 tables. these tables indexed by domain name. so if four tables go开发者_开发问答t domain name which is updating then it will update all table otherwise it wont. but I want add that domain and info to table which does not have the same info.

right now I am using normal update query

mysql_query("UPDATE LOW_PRIORITY dscrpn SET descr='$descr',title='$title' WHERE web='".mysql_real_escape_string($urweb)."'");


You can't (as far as I know) write one single statement that will either update the existing row, or insert a new one if it doesn't exist.

What you can do is send an update, then check the number of rows affected by the update (mysql_affected_rows); if it had zero rows affected, then do an insert. You could do this all in MySQL, but I'd probably just do it in the PHP code.


see http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html

self-contained example (using PDO):

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($pdo);

$stmt = $pdo->prepare('
    INSERT INTO
        so_dscrpn
        (web,descr,title)
    VALUES
        (?,?,?)
    ON DUPLICATE KEY UPDATE
        descr=VALUES(descr),
        title=VALUES(title)
');
$data = array(
    array('uri1', 'desc1', 'title1'),
    array('uri2', 'desc2', 'title2'),
    array('uri1', 'desc3', 'title3')
);
foreach($data as $row ) {
    $stmt->execute($row);
}

foreach( $pdo->query('SELECT * FROM so_dscrpn', PDO::FETCH_ASSOC) as $row ) {
    echo join(', ', $row), "\n";
}

function setup($pdo) {
    $pdo->exec('
        CREATE TEMPORARY TABLE so_dscrpn (
            web varchar(48) NOT NULL,
            descr varchar(48),
            title varchar(48),
            unique key(web)
        )
    ');
}

prints

uri1, desc3, title3
uri2, desc2, title2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜