Pergunta

Please help me optimize the following foreach loop. It works perfectly with small arrays, when the loop is short but the problem is that sometimes, when the array is way to big, it forces the query to loop inside the foreach to many times, and that is causing my server to jam throwing a 503 error. I need to somehow do the query outside the foreach but still be able to select WHERE cat=$id[0] AND sub = $id[1] AND fir = $id[2].

foreach($array as $id){
    $query=mysqli_query($con,"SELECT * FROM table WHERE cat=$id[0] AND sub = $id[1] AND fir = $id[2]");

    $thiss = mysqli_fetch_array($query);
    echo $thiss['name']; 
}
Foi útil?

Solução

I am not going into the details of why I suggest you should reconsider your query logic, but for the task at hand try this:

$where=array();
foreach($array as $id){
  $where[]="cat=$id[0] AND sub = $id[1] AND fir = $id[2]";
}
$sql='SELECT * FROM table WHERE ('.implode(') OR (',$where).')';
$query=mysqli_query($con,$sql);
while ($thiss = mysqli_fetch_array($query))
  echo $thiss['name']; 

Outras dicas

$ands = array();
foreach ($array as $id) {
    $ands[] = "(cat=$id[0] AND sub = $id[1] AND fir = $id[2])";
}
$ors = implode(' OR ', $ands);
$query = mysqli_query($con, "SELECT name FROM TABLE WHERE $ors";
while ($thiss = mysqli_fetch_assoc($query)) {
    echo $thiss['name'];
}

Try this

$cat = $sub = $fir = '';
foreach($array as $id){
  $cat .= $id[0].',';
  $sub .= $id[1].',';
  $fir .= $id[2].',';
}
$cat = substr_replace($cat, '', -1);
$sub = substr_replace($sub, '', -1);
$fir = substr_replace($fir, '', -1);
$sql = "SELECT * FROM table WHERE `cat` IN ($cat) AND `sub` IN($sub) AND `fir` IN ($fir)";
$query=mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($query)) {
   echo $row['name']; 
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top