Home PHP mysql query issue when filtering from array and variables
Reply: 0

PHP mysql query issue when filtering from array and variables

user2582 Published in April 20, 2018, 10:50 am

On my webpage (html, php), I'm trying to get it such that users may select multiple checkboxes, each checkbox effectively filters what results the users see. Info is pulled from the database (MySQL) based on the values in different columns. As shown below, one column is Joint_1, another column is Position.

Effective code that WORKS for filtering (very static, not practical to use obviously) is this:

$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'region1\'  OR  
                                          Joint_1=\'region2\'  OR  
                                          Joint_1=\'region3\' OR
                                          Joint_1=\'region4\') AND
                                         (Position=\'position1\' OR
                                          Position=\'position2\' OR
$result = $conn->query($sql);

if($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
      echo $row["Common_Name1"] . "<br>";
} else {
  echo "0 results";

Below code is attempts at above code, but using arrays, which does NOT work.

$regions = 
array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');

$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'. $regions[0] .\'  OR  
                                          Joint_1=\'. $regions[1] .\'  OR  
                                          Joint_1=\'. $regions[2] .\' OR
                                          Joint_1=\'. $regions[3] .\') AND
                                         (Position=\'. $position[0] .\' OR
                          Position=\'. $position[0] .\' OR
                      Position=\'. $position[0] .\')"; 

Above code provides results of '0 results.'

I've attempted to perform this numerous times, with additional NON-FUNCTIONAL CODE also below (below attempting to filter based on only 1 column as I have obviously not mastered the code to approach filtering based on 2 columns).

$sqlregion = array();
foreach ($_POST['region'] as $reg) {
   $sqlreg[] = "'" . mysql_real_escape_string($reg) . "'";   
$sql = "SELECT * FROM 'Exercises' WHERE Joint_1 IN (" . implode(",", 
$sqlreg) . ");";


if($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
     echo $row["Common_Name1"] . "<br>";

Any help is appreciated! Thanks.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.361579 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO