phpmysqlmysqliphp-mysqlidb

Call to a member function fetch_field() on a non-object MySQLiDB


Hi i cant use INSERT UPDATE function with this class: MySQLiDB. Im trying write data to mysql and if exists this data then need update. So i use INSERT ... ON DUPLICATE KEY UPDATE.... My code like this:

$db->rawQuery("INSERT INTO table1 (field1,field2,field3) VALUES (?,?,?) ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)", array("value1",value2,value2));

this code works fine. But when use this code in cycle and give values by another array shows me this error: Call to a member function fetch_field() on a non-object in.... This is code in cycle:

$db->rawQuery("INSERT INTO table1 (field1,field2,field3) VALUES (?,?,?) ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)", array($value[$i][value1],$value[$i][value2],$value[$i][value3]));

What i can do in this situation?


Solution

  • Do not use MySQLiDB. It is unusable in many ways.

    You can use safemysql instead:

    $sql = "INSERT INTO table1 (field1,field2,field3) VALUES (?s,?s,?s) 
            ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)";
    $db->query($sql, $value[$i]['value1'],$value[$i]['value2'],$value[$i]['value3']);
    

    Or, in a much simpler way:

    foreach ($value as $row)
    {
        $sql = "INSERT INTO table1 SET ?u
                ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)";
        $db->query($sql, $row);
    }
    

    (only if $value coming from the trusted source though)

    You could also create a query for the single insert

    $ins = array();
    foreach ($value as $row) {
        $ins[] = $db->parse("(?s,?s,?s)",$row['value1'],$row['value2'],$row['value3']);
    }
    $instr = implode(",",$ins);
    $sql = "INSERT INTO table1 (field1,field2,field3) VALUES ?p 
            ON DUPLICATE KEY UPDATE field2=VALUES(field2),field3=VALUES(field3)";
    $db->query($sql, $ins);