php - SQLite update is replacing fields with null values -
okay ive been reading on , working sqlite (someone on here suggested actually).
it works great need - in-memory database. problem having duplicate records in here wanted insert record if exists fill in missing fields.
now first method tried setting id primary key , insert or replace into. issue previous contents being wiped out.
so im doing update query. im them checking number of rows changed. if below 1 run insert query (if there better way share know has overhead).
anyway issue (finally).. update query records being overwritten null values.
ive condensed snippets of code below:
$stmt1 = $db->prepare("update results set field1=?, field2=?, field3=? id=? "); $stmt1->execute(array( $elm['content1'], $elm['content2'], $elm['content3'], $elm['id'] )); $count = $stmt1->rowcount(); if ($count < 1) { $stmt2 = $db->prepare("insert results (id, field1, field2, field3) values (:id,:field1, :field1, :field1 ) "); $stmt2->execute(array(":id" => $recordid, ":field1" => $elm['content1'], ":field2" => $elm['content2'], ":field3" => $elm['content3'])); }
the above going on within foreach loop.
is anyway stop content being overwritten if in db. if on update field null add new content, if got in leave unaltered , move on next field. ive read ifnull can used in sqlite im not sure how use within pdo prepared statements.
any help, guidance, examples appreciated :)
p.s im using php5 sqlite
if on update field null add new content, if got in leave unaltered , move on next field.
you can use coalesce
this; here example:
~ e$ sqlite3 sqlite version 3.7.5 enter ".help" instructions enter sql statements terminated ";" sqlite> create table foo (a,b,c); sqlite> insert foo values (1,null,3); sqlite> select * foo; 1||3 sqlite> update foo set = + 1, b = coalesce(b,'b'), c = coalesce(c,'c'); sqlite> select * foo; 2|b|3 sqlite>
so, stmt1
be:
$stmt1 = $db->prepare("update results set field1=coalesce(field1,?), field2=coalesce(field2,?), field3=coalesce(field3,?) id=? ");
Comments
Post a Comment