How to handle a n:m relation correctly with PHP&MySQL? -


i've got 3 tables:

 +-----------------+ |   validations   | +----+-------+----+ | id | param | ... +----+-------+ 
 +------------------+ |   replacements   | +----+-------------+ | id | replacement | +----+-------------+ 
 +--------------------------------+ |    validations-replacements    | +---------------+----------------+ | validation_id | replacement_id | +---------------+----------------+ 

now i'm running sql query on tables (with joins of course). , receive in php sth. that:

 ... [6] => stdclass object (     [id] => 11     [search_param] => dänische belletristik     [replacement] => denmark )  [7] => stdclass object (     [id] => 11     [search_param] => dänische belletristik     [replacement] => fiction ) ... 

now, in php-array i've got same 'search_param' , 'id' multiple times. sucks printing screen. group data 'id' avoid that, i've got 1 'replacement' value available.

what i'm looking result this:

 ... [7] => stdclass object (     [id] => 11     [search_param] => dänische belletristik     [replacement] => array(denmark, fiction) ) ... 

what want know: possible table structure fixing query? or have care in php-code - if so: hints how best? there's plenty of data... table structure correct? i'm still bit uncertain when comes databases...

best regards.

it looks want show replacements search param? assuming query like:

select *  validations_replacements vr  inner join validations v on v.id = vr.validation_id  inner join replacements r on r.id = vr.replacement_id v.param = '$search_param' 

you can either group them in php playing result array, assuming results object $results:

$replacements = array() ; foreach ($results $result) {     $currsearchparam = $result['search_param'];     $currreplacement = $result['replacement'] ;     if (!isset($replacements[$currsearchparam])) {         $replacements[$currsearchparam] = array() ;     }     $replacements[$currsearchparam][] = $currreplacement; }  //i'll let fill in blanks object id or naming array keys wish 

or can in mysql, iterate on result in php:

select v.id, v.param, group_concat(r.replacement) validations_replacements vr  inner join validations v on v.id = vr.validation_id  inner join replacements r on r.id = vr.replacement_id v.param = '$search_param' group v.id 

with group_concat single result line each search param, , replacements in comma separated string, can work iterating on result in php:

$replacements = array() ; foreach ($results $result) {     $currsearchparam = $result['search_param'];     $currreplacements = $result['replacements'] ;     $replacements[$currsearchparam] = explode(',', $currreplacements) ; } 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

sql server - python to mssql encoding problem -

windows - Python Service Installation - "Could not find PythonClass entry" -