Hi, i have a string containing tables name dynamicaly like
$str="tbl1,tbl2,tbl3,tbl4"; now from here i want to create a part of query like
tbl1.id=tbl2.id and tbl2.id=tbl3.id and tbl3.id=tbl4.id
id is fixed value so no worry about it.
thanks
$str="tbl1,tbl2,tbl3,tbl4"; $a=explode(",",$str); // becomes $a[0]=='tbl1', $a[1]=='tbl2', etc. $asize=sizeof($a); $sql=''; for($i=0;$i<($asize-1);$i++) { $sql.= $a[$i] . '.id=' . $a[$i+1] . '.id and '; } // remove last ' and ' $sql=substr($sql,0,-5); echo "<hr>".$sql;
Why use a string when an array is much better suited for the job?
I'd do something like this:
$tables = array('tbl1', 'tbl2', 'tbl3', 'tbl4'); $query = 'SELECT * FROM your_table WHERE '; //finish the first part of your query here for ($i = 0; $i < count($tables) - 1; $i++) { $query .= $tables[$i] . '.id=' . $tables[$i+1] . '.id'; //Add this part to prevent an ' AND ' from being added in the last iteration. if ($i != count($tables) - 2) { $query .= ' AND '; } } echo $query;
Damn you, Iron Man! You have faster fingers than I, my friend =)
huh what... do we win anything here for posting a solution first? :p
(that should be a drool not a strawberry)