简体   繁体   中英

MYSQL query update or insert in PHP using if else

$getCoins = $this->code = $this->conn->prepare("UPDATE coins SET name = ? WHERE id_name = ? IF @@ROWCOUNT = 0 INSERT INTO coins (id_name) VALUES (?)");

for ($i=0; $i < count($coins) ; $i++) { 

    $id_name = $coins[$i]["id"];
    $name = $coins[$i]["name"];


    $getCoins = $this->code->bind_param('sss', $name, $id_name, $id_name);
    $getCoins = $this->code->execute();
    $getCoins = $this->code->store_result();

}

Script return me error:

Fatal error: Uncaught Error: Call to a member function bind_param() on boolean ...

The problem is with IF @@ROWCOUNT = 0 I tryied using IF ELSEl

IF(SELECT COUNT(id_name) FROM coins WHERE id_name = 'bitcoin')
    UPDATE coins SET name = 'xxx2' WHERE id_name = 'bitcoin'
ELSE
    INSERT INTO coins (name) VALUES ('new_coins')
END IF

but hear is error:

#1064 - Something is wrong in your syntax obok 'UPDATE coins SET name = 'xxx2' WHERE id_name = 'bitcoin' ELSE INSERT INTO coi' w linii 2

I using this answer link

Use the ON DUPLICATE KEY UPDATE option to INSERT .

INSERT INTO coins (id_name, name)
VALUES (?, ?)
ON DUPLICATE KEY UPDATE name = VALUES(name)

If id_name already exists, the name column will be updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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