Jump to content

Updating MySQL table with multiple updates


AdRock

Recommended Posts

I have a function that updates a database and it works fine for one record but i have a form which shows loads of rows with checkboxes and i want to do a batch update (I suppose the principle is the same for a batch delete).

 

When I click a load of checkboxed and call the funtion to update, i get an error about an array to string conversion and also this error message "Unknown column 'Array' in 'where clause"

 

I know a way around it but it's not great using a foreach loop to update the database but that involves loads of queries

 

This is my function I call to update the database

 /**
     * update
     * @param string $table A name of table to insert into
     * @param string $data An associative array
     * @param string $where the WHERE query part
     */
    public function update($table, $data, $where)
    {
        ksort($data);
        
        $fieldDetails = NULL;
        foreach($data as $key=> $value) {
            $fieldDetails .= "`$key`=:$key,";
        }
        $fieldDetails = rtrim($fieldDetails, ',');
        
        $sth = $this->prepare("UPDATE $table SET $fieldDetails WHERE $where");
        
        foreach ($data as $key => $value) {
            $sth->bindValue(":$key", $value);
        }
        
        $sth->execute();
    }

This works

public function newsEdit($data) {
    
        $postData = array(
            'title' => $data['news_title'],
            'content' => $data['news_content'],
            'photo' => $data['imgname'],
            'keywords' => $data['news_keywords'],
            'alternate' => $data['alternate']
        );
        
        $this->db->update('news', $postData, "`id` = {$data['newsid']}");
    }

$data = array();
                    
$data['news_title'] = $_POST['news_title'];
$data['news_content'] = $_POST['news_content'];
$data['imgname'] = $_POST['imgname'];
$data['news_keywords'] = $_POST['news_keywords'];
$data['alternate'] =  substr($_POST['imgname'],0,strrpos($_POST['imgname'], "."));               

newsEdit($data);

This doesn't

public function newsArchive($ids) {
    
        $postData = array(
            'archived' => 'Y'
        );
        
        $this->db->update('news', $postData, "`id` IN ({$ids})");
    }

newsArchive($_POST['id']);

What have i got to change to get the update working?

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.