I have developed a script using Yii MVC and i have a problem with the index keys and criterias.
I want to prevent the insertion of a record that is already stored in the database;
My example, fails to check and tries to add a new record each time.
Why ? And how to do this ?
CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '21-/popular/category/1.html' for key 'index_link'. The SQL statement executed was: INSERT INTO `categories` (`server_id`, `website_id`, `slave_category_id`, `link`, `name`, `image`, `videos`, `status`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7)
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`server_id` int(11) NOT NULL,
`website_id` int(11) NOT NULL,
`slave_category_id` int(11) NOT NULL,
`link` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`image` varchar(255) NOT NULL,
`videos` int(11) NOT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `index_link` (`website_id`,`link`),
UNIQUE KEY `index_name` (`website_id`,`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=332 ;
the PK is id;
another index, is website_id + link;
another index is website_id + name;
the following code fails to check and prevent the insertion:
1
$criteria_categories = new CDbCriteria();
$criteria_categories->condition = " `server_id`=':server_id' and `website_id`=':website_id' and `link`=':link' and `name`=':name' ";
$criteria_categories->params = array(
':server_id' => $model_website->server_id,
':website_id' => $model_website->id,
':link' => $matches_url[$value->link][$key2],
':name' => $matches_url[$value->name][$key2],
);
$record_categories = Categories::model()->find($criteria_categories);
print_r($record_categories);
if (!$record_categories) {
$model_categories = new Categories();
$model_categories->server_id = $model_website->server_id;
$model_categories->website_id = $model_website->id;
$model_categories->slave_category_id = 1; //??
$model_categories->link = $matches_url[$value->link][$key2];
$model_categories->name = $matches_url[$value->name][$key2];
$model_categories->image = $matches_url[$value->image][$key2];
$model_categories->videos = 0;
$model_categories->status = 0;
$model_categories->save();
}
You have a couple errors going on. One is syntax. If using the parameter binding (which is a good thing to use), you don’t want to quote the parameters.
That is, write
:linkinstead of':link'.The above condition also does not correctly check for existing records that have either of your two unique keys. Try the following:
This both quotes correctly and will find the record if either of your two unique keys match, rather than requiring both to match.