根据PHP中的因素创建SQL查询

时间:2013-01-28 19:46:35

标签: php sql select wildcard

你好我一直坚持这种方法一段时间了。

将值从Android传递到PHP以与数据库连接。可能会或可能不会有因素传递给该方法(例如$baseLocation可能为空)。

任何变量都可能为null但我想构建依赖于传递的SQL查询。

这是我的代码:

public function searchForPeople($tower, $baseLocation, $clientSite, $graduate, $currentLocation) {
        $uuid = uniqid('', true);

        $terms = array();
    $values = array();

    if (isset($tower)) {
       $terms[] = "tower = ?";
       $values[] = $tower;
    }

     if (isset($baseLocation)) {
       $terms[] = "baseLocation = ?";
       $values[] = $baseLocation;
    }


    $query = "SELECT * FROM users ";

    if ($terms) {
        $query .= " WHERE " . join(" AND ", $terms);
    }

        $result = mysql_query($query) or die(mysql_error());


        //$result = mysql_query("SELECT * FROM users WHERE tower='$tower' AND show_location = 1") or die(mysql_error


        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {

                $return_arr = array();

                while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

                    $row_array['name'] = $row['name'];
                    $row_array['email'] = $row['email'];
                    $row_array['current_location'] = $row['current_location'];
                    $row_array['tower'] = $row['tower'];
                    $row_array['base_location'] = $row['base_location'];
                    $row_array['client_site'] = $row['client_site'];
                    $row_array['graduate'] = $row['graduate'];
                    $row_array['location_updated'] = $row['location_updated'];
                    $row_array['role'] = $row['role'];

                    array_push($return_arr,$row_array);
                }

            $result = json_encode($return_arr);

            return $result;

        } else {
            // user not found
            return false;
        }
        }

0 个答案:

没有答案