0
$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

7
  • delimit your statements with ';' and seems odd if you put all your query in one call. Commented Jan 23, 2018 at 20:04
  • @maSTAShuFu Like this: UPDATE coins SET name = 'xxx2' WHERE id_name = 'bitcoin'; IF @@ROWCOUNT = 0; INSERT INTO coins (name) VALUES ('new_coins'); I have error: #1193 - Unknown system variable 'ROWCOUNT' Commented Jan 23, 2018 at 20:11
  • @michal @@ROWCOUNT doesn't exist in MySQL. It's a SQL Server construct. Commented Jan 23, 2018 at 20:11
  • but normally you don't do this kind of coding Commented Jan 23, 2018 at 20:13
  • @flip Yes, you're right, but why dont work second solution, when I use If and else Commented Jan 23, 2018 at 20:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.