Magento 2 – How to Write MySQL Update Query

databasemagento2

In ResourceModel model I need to execute update query.

$sql = "UPDATE 2067_ci_sessions SET data='$cisess_data' WHERE id= $id";

instead of writing direct mysql query how can i write update query in magento 2 format?. Thanks in advance for your valuable answer

public function clearMlmSession($cisess_data, $cisess_cookie)
{   

    $table = "2067_ci_sessions";
    $bind = ['id' => $cisess_cookie];

    //For user information
    //select query
    $connection = $this->getConnection();
    $select = $connection->select()->from(
        $table,
        ['data']
    )->where(
        'id = :id'
    )->limit(
        1
    );
    $cisess_data = $connection->fetchRow($select, $bind);
    //$cisess_data = decode_session_data($cisess_data);
    if (empty($cisess_data)) {
        return false;
    }
    //select query


    //Update Data into table
    $sql = "Update " . $table . " Set data = '$cisess_data' where id = '$cisess_cookie'";
    $result = $connection->exec($sql);
    //$result = $connection->exec($sql);

    print_r($result); die("debug");
}

In this function select working correctly like that i need write update, i wrote my update query directly. how to write this update query in magento 2 format?

Best Answer

OK now I get your point. It's legistimate to use update SQL.

According to the Github belongs to Marius, this is the SQL way:

$this->getConnection()->update(
    $object->getResource()->getTableName($table),
    $cisess_data,
    ['id = ?' => (int)$cisess_cookie]
);

Replace the above code after the comment //Update Data into table.

BTW @Piyush, never use Object instance :)

Related Topic