mardi 23 janvier 2018

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

Aucun commentaire:

Enregistrer un commentaire