Using CakePHP 1.3 I’m trying to save some data to a MySQL database. The data doesn’t come from a form, but to imitate it I put the data in the $this -> data array like this:
$this -> data = Array (
'User' => Array (
'last_login' => date ('Y-m-d H:i:s')
)
);
This creates an array that looks exactly like the default Cake data array. So far so good.
Next, I call the following function:
if ($this -> User -> save ($this -> data))
{
echo $this -> User -> id;
}
else
{
echo 'Save failed';
}
It always comes up with ‘Save failed’, showing the data wasn’t saved correctly. I tried to debug this in a variety of ways:
I checked whether a beforeSave or beforeValidate function existed in my User model or AppModel and whether these return true. (They did.)
I echoed $this -> Session -> flash () in default.ctp. It doesn’t say anything.
I echoed $this -> element ('sql_dump') in default.ctp. I don’t see any sign of the query I expect, confirming my expectation of the query not executing instead of just failing.
From my controller I echoed $this -> validationErrors. It’s empty so validation seems to be ok.
I tried to provide the correct index in my $this -> data array for the save, like this:
$this -> User -> save ($this -> data['User']);
I checked whether I loaded my User model via $this -> loadModel ('User') (I did).
Note that I try to do this in my AppController (that’s why I loaded the model manually). More specifically: it’s in the beforeFilter () function in the AppController. This function is called in the beforeFilter () function in every other Controller my application has (I checked this).
At the moment, I don’t know what could cause this. Does anyone have an idea about this?
You’re not specifying the User id before you save, so CakePHP has no idea what row to save the date to. In effect, you’re asking CakePHP to just save a date, without specifying where. I am away from my webdev box right now, but I believe this is what you’re looking for.
See this page for more information. BTW, if you want to do it the way you were originally doing it, I think this is the way: