Namit
Namit

Reputation: 1322

mysql statement using a for loop php

I have a mysql query which is being to find the stock items in a certain location belonging to a certain group. Hence this is going through 4 levels of while loops. No i have given the user the ability to select the locations they want to view the stocks from. This is being achieved using checkboxes which are sent using ajax in an array. The array exploded in PHP using $offices = explode(",", $locations);. However now i want to use the locations selected in my mysql query.

$location are in the form of location1, location2, location3, location4

//selecting all locations using the statement below, however i want to select the locations that where selected by user.

$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where 'wanted locations');
    while($row3 = mysql_fetch_array($sql4)) {
        $curr_location = $row3[0];

        $sql3 = mysql_query("select Quantity from Stock_Management where Book_ID = '$curr_book' and Location_ID = '$curr_location'");
        while($row3 = mysql_fetch_array($sql3)) {
            echo "<td>".$row3[0]."</td>";
        }   
    }
    echo "</tr>";

I want to select the locations based on the selected locations by user, now this can be achievable using a for loop by i don't know how to include that in my sql query!

Upvotes: 1

Views: 130

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157839

$locations = mysql_real_escape_string($locations);
$locations = str_replace(",","','",$locations);

$sql = "select OfficeID, OfficeTitle from Office WHERE location in ('$locations')";

Upvotes: 1

Namit
Namit

Reputation: 1322

$offices = explode(",", $locations);
$loc =  implode("','", $offices);

This helps is creating the variable $loc to location1','location2',location3

$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where OfficeTitle IN ('$loc')");

This creates the mysql query to be:

$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where OfficeTitle IN ('location1','location2',location3')");, which solves the purpose for now.

Upvotes: 1

Straseus
Straseus

Reputation: 478

SELECT OfficeID, OfficeTitle FROM Office WHERE OfficeID IN ( $locations ); ??

Also, look up mysql_real_escape_string and 'separation of concerns`

Upvotes: -1

Related Questions