开发者

Need help using UNIQUE keys on several columns

I have the following table:

Need help using UNIQUE keys on several columns

As you can see index_lang is a unique key that constrain the couple nid/ language.

Now if i insert values for nid and languages to something like this:

Need help using UNIQUE keys on several columns

How then can i check with PHP if a row with a pair nid / language have already be inserted into that table as it seems that i can not retrieve the value of the index_lang key. I was assuming that this index_lang key would automatically get the value of the 2 column inserted, so according to the above table the row 1 unique key would get a value of : '1chinese'

EDIT: I am using drupal API to insert data in this table, the PHP code that insert the data right now looks like this:

foreach ( $user_lang as $k=>$v ){
    $lang_query = db_insert('my_table')
      ->fields(array(
        'nid' => $og_group->etid,
        'language' => $v))
      ->execute();  
}
开发者_C百科

$user_lang is an array of languages.

Second Edit:

I would us an IGNORE statement to insert my data to avoid duplicate and ignore errors though there is no such thing using the Drupal DB API, well if there is i have no ideas on how to do..


An index is not the same as a column. It is used for internal use by mysql and you can't read it as a column.

The above however should prevent you from inserting double entries. Just check it by trying to add a row with nid=1 and language="Chinese". You should get an error message (unique key violation.)

From php you could try to insert the row. If you just need it to not insert, you can use the error message to display something to the user.

If you want the current value updated you could use ON DUPLICATE KEY UPDATE in your sql.

And finally you could of course first do a select ... from languages where nid=1 and language="Chinese" and then decide what you want to do with it.


First think of the SQL. You would need this query

SELECT COUNT(*) FROM table_name WHERE nid=1 AND language='Chinese'

From this you can easily get the PHP - whose query will depend of if you are using mysql or mysqli


You cannot retrieve the value of index_lang it's an index.

SELECT 1 FROM mytable WHERE nid=1 AND language='Chinese'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜