使用for循环php的mysql语句

时间:2012-03-17 13:14:46

标签: php

我有一个mysql查询,用于查找属于某个组的特定位置的库存商品。因此,这将经历while loops的4个级别。不,我已经让用户能够选择他们想要查看股票的位置。这是使用复选框实现的,复选框是使用数组中的ajax发送的。使用exploded in PHP的数组$offices = explode(",", $locations);。但是现在我想使用我的mysql查询中选择的位置。

$location采用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>";

我想根据用户选择的位置选择位置,现在这可以使用for循环实现,我不知道如何在我的sql查询中包含它!

3 个答案:

答案 0 :(得分:1)

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

这有助于创建变量$loclocation1','location2',location3

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

这将创建mysql查询:

$sql4 = mysql_query("select OfficeID, OfficeTitle from Office where OfficeTitle IN ('location1','location2',location3')");,它解决了目前的目的。

答案 1 :(得分:1)

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

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

答案 2 :(得分:-1)

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

另外,查看mysql_real_escape_string和“关注点分离”