pass variable to mysql statement in foreach loop

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
phillyrob0817
Forum Newbie
Posts: 2
Joined: Sun Mar 15, 2015 10:39 am

pass variable to mysql statement in foreach loop

Post by phillyrob0817 »

Is there a way to use another variable in a mysql select where statement for inside a foreach loop.

Ex:

<?php

This works fine.

Code: Select all

    foreach ($range as $b)
            {

     $result = $conn->query("select count(*) as mycount1  from $table where date >= '$date' and (Ball1  = $b or Ball2  = $b or Ball3  = $b or Ball4  = $b or Ball5 = $b)");

      while ($row = $result->fetch_object()) {
       $count  = $row->mycount1;
       echo  $b." ".$count."<br>";
       }

      }


But, I want to be able to use this variable string below* in my statement so I can change what comes after the "and" in the statement. Is there a way to do that?

Code: Select all

    *$ballsB5 = ("Ball1  = $b or Ball2  = $b or Ball3  = $b or Ball4  = $b or Ball5 = $b");


    foreach ($range as $b)
            {

       $result = $conn->query("select count(*) as mycount1  from $table where date >= '$date' and $ballsB5");

      while ($row = $result->fetch_object()) {
       $count  = $row->mycount1;
       echo  $b." ".$count."<br>";
       }

      }


?>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: pass variable to mysql statement in foreach loop

Post by Celauran »

Move the parentheses inside the quotes so your OR conditions are grouped like you want, then move the variable assignment back inside your foreach loop. Better still, create a prepared statement outside of the loop and execute inside.
phillyrob0817
Forum Newbie
Posts: 2
Joined: Sun Mar 15, 2015 10:39 am

Re: pass variable to mysql statement in foreach loop

Post by phillyrob0817 »

Thanks for the replies and am trying the suggestions now.
Post Reply