what's the best approach should i adopt for this php problem
Note: This q开发者_如何学Cuestion is posted here
hello everybody, I have a predefind list of 15 keywords and there is mysql table against each keyword. Now what i want to do is that first i want to check a keyword and then insert it into the relevant table. This process continue agian and again under foreach loop. My question is what kind of approach should i used i.e is it with if else statements, likeforeach($keyword as $key=>$val) { if($val==='keyword1' { $query="insert into keyword1_tab values('', $val); $rs=mysql_query($query) or die(mysql_error()); } else if($val==='keyword2') { $query="insert into keyword2_tab values('', $val); $rs=mysql_query($query) or die(mysql_error()); } else . . . . . else if($val==='keyword15') { $query="insert into keyword3_tab values('', $val); $rs=mysql_query($query) or die(mysql_error()); } }Or something else is used for this which can maintain the speed and consistency.
$tables = array('keyword1' => 'keyword1_tab', 'keyword2' => 'keyword2_tab' ...);
foreach($keyword as $key=>$val)
{
if (isset($tables[$val]))
{
$query="insert into `".$tables[$val]."` values('', '".$val."')";
$rs = mysql_query($query) or die(mysql_error());
}
}
You should use just one table. Period.
That's the only proper way.
Using separate tables for the same matter is against all rules.
You need to learn basics of relational databases design and make your database schema fit into these basic rules.
I see not much sense in these inserts though. What are you doing in general? What is purpose of all that inserts?
You could always make it prettier using a switch case:
foreach($keywords as $key=>$val){
$query = "";
switch($val){
case "keyword1":
$query = "YOUR_QUERY_HERE";
break;
case "keyword2":
$query = "YOUR_QUERY_HERE";
break;
}
if(query != ""){
$rs = mysql_query($query) or die(mysql_error());
}
}
精彩评论