Update existing records without insertion new

I've got a table with bunch of per-user configurations and each row contains user id, name of config, value of config 11 rows per user. Now when I try to update existing records I get +11 duplicate rows instead. Here is my update action:

    public function updateAction($uid)
    {
        if ($this->request->isPost()) {
            foreach ($this->request->getPost() as $name => $value) {
                $config = Configs::findFirst("user_id = '".$uid."' AND name = '".$name."'"); 
                $config->name = $name;
                $config->value = $value;
                $config->user_id = $uid;
                $config->update();
            }
            $this->dispatcher->forward(array(
                'controller' => 'config',
                'action' => 'index'
            ));
        }
    }

I think it occurs because your config table doesn't have primary key or unique constraint



2.6k

Ok, it doesnt have it indeed, but is there any other way to create/update records in tables without those keys?

Why you want this in a wrong way????

each table should have a primary key.

Yes there are another ways too but it's not correct to use them. every other way is unreliable.

I would say the same as commented above. As much as I would like to help here there is no way you can work on a database table which don't have atleast one column that uniquely identifies its data. If I may ask how are you setting the user id.

Otherwise replace your function with the one below and let me know

    public function updateAction($uid)
{
    if ($this->request->isPost()) {
        foreach ($this->request->getPost() as $name => $value) {
            $config= Configs::find("user_id = '".$uid."' AND name = '".$name."'"); 
            $config['0']->name = $name;
            $config['0']->value = $value;
            $config['0']->user_id = $uid;
            $config['0']->update();
        }
        $this->dispatcher->forward(array(
            'controller' => 'config',
            'action' => 'index'
        ));
    }
}


2.6k

Thank you all this is working with index