shank shank - 3 months ago 7
MySQL Question

update query throws error in mysql

I have a table named 'mostread' with 2 columns open_id(int) and read(int). Now the problem is if 'open_id' is already present in the table then i need to update the 'read' for every click else i need to insert a new row with 'open_id' retrieved from the controller and read=1. I am using the below code in my model which inserts a new row properly but the second time i click it throws an error as follows.

A Database Error Occurred


Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'read = read+1 WHERE
open_id
= '193'' at line 1

UPDATE
mostread
SET read = read+1 WHERE
open_id
= '193'

Filename: D:/Xampp/htdocs/opunletter/opunletter/application/models/Select.php

Line Number: 52


public function click($id)
{
$query = $this->db->query("SELECT * FROM mostread WHERE open_id='$id'");

$count= $query->num_rows();
if($count > 0) {
$this->db->set('read', 'read+1', FALSE);
$this->db->where('open_id', $id);
$this->db->update('mostread');

$data = array(
'open_id' => $id,
'read' => '1'
);

$this->db->insert('mostread', $data);
return TRUE;
}else{
return FALSE;
}
}

Answer

Try adding backticks arround read its a reserved keyword in mysql

$this->db->set('`read`', '`read` + 1', FALSE);