sql - How to do multiple INNER JOIN dynamically in php -
this first i've made code using multiple inner join
s relationship table.
this i'm doing:
$table = $_post['tabla']; $campos = $_post['campos']; $camporelacion = $_post['campo_relacion']; **//code forget put** *// create array contain fields $ field = array (); //walk array of fields , assigned array //that created foreach ($ fields $ val) { $ field [] = "". $ val. ""; } //we separate fields in array commas $ field = join (',', $ field);* $maintable = $table[0]; $sql = 'select '.$field.' '.$maintable.' '; ($i = 1; $i<count($table); $i++) { $curtable = $table[$i]; $joinfield = $camporelacion[$i-1]; $sql.= 'inner join '.$curtable.' on '.$maintable.'.'.$joinfield.' = '.$curtable.'.'.$joinfield.' '; }
the output of depending on data send:
select slip_plantillas.nombre, cat_reaseguradoras.nombre, slips.numero_referencia, slips.asegurado_original, tipo_operaciones.nombre slips inner join slip_plantillas on slips.slip_plantillaid = slip_plantillas.slip_plantillaid inner join cat_reaseguradoras on slips.cat_reaseguradoraid = cat_reaseguradoras.cat_reaseguradoraid inner join tipo_operaciones on slips.tipo_operacionid = tipo_operaciones.tipo_operacionid
as shown in table above, code slips remains constant in joins.
but have sql statement want make slips not constant , change unions.
the query looks this:
select slip_dos_reasegurado.prima_cien, slip_dos_reasegurado.porcentaje_aseguradora, cat_reaseguradoras.nombre, slip_dos_capas.capa, slip_dos_capas.prima_capa, slip_dos_pagos.cantidad, slip_dos_pagos.referencia, estatus.nombre, slips.tipo_negocio slips inner join slip_dos_reasegurado on slips.slipid = slip_dos_reasegurado.slipid inner join slip_dos_capas on slip_dos_capas.slip_dos_reaseguradoid = slip_dos_reasegurado.slip_dos_reaseguradoid inner join slip_dos_pagos on slip_dos_capas.slip_dos_capaid = slip_dos_pagos.slip_dos_capaid inner join cat_reaseguradoras on cat_reaseguradoras.cat_reaseguradoraid = slip_dos_reasegurado.cat_reaseguradoraid inner join estatus on estatus.estatusid = slip_dos_pagos.estatusid
as can see, relations no longer single table if not mixed each other depending on field relationship.
maybe need ?
<?php $tables = array('tbl1','tbl2','tbl3','tbl4'); $columntable = array('column1','column2','column3','column4'); $columnrelation = array('column_relation1','column_relation2','column_relation3','column_relation4'); $maintable = $tables[0]; $sql = 'select * '.$maintable.' '; foreach($tables $index=>$tbl){ if($index == 0) continue; //normal while know array indexes start 0, in other case need variable $sql .= 'inner join $tbl on '.$tbl.'.'.$columntable[$index].' = '.$tables[$index-1].'.'.$columnrelation[$index-1].' '; } echo $sql; ?>
Comments
Post a Comment