trante trante - 6 months ago 25
PHP Question

How do I properly save data to the database?

I normally save new data to the database like this:

'id' => $id,
'code' => $temp_code,
'status' => $status,
'age' => $age,
'location' => $location,
'money' => $money


If the ID already exists in the database I update its corresponding fields like this:

$this->Adtweet->id = $id;
$this->Adtweet->saveField('code', $temp_code);
$this->Adtweet->saveField('status', $status);

Is there a better or 'proper' way to do this?

When I attempt to enter an ID that already exists and I use the
function, I get the following SQL integrity error:

(Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '150245925' for key 'PRIMARY')

How can I write a function that cleanly handles duplicate entries without returning an error?


If you want to save new data, just use Model::save():

$data = array(
    'ModelName' => array(
        'foo' => $foo

// prepare the model for adding a new entry

// save the data

If you want to update your data just use the same method without calling Model::create()

$data = array(
    'ModelName' => array(
        'id' => $id
        'foo' => $foo


See also:


I guess this is what you're looking for:

$this->ModelName->id = $id;
if (!$this->ModelName->exists()) {