将Array的内容添加到SQL查询中的Condition中

时间:2013-11-18 10:44:19

标签: php mysql

我正在尝试使用这个函数get()来获取将在WHERE中使用的tbl_name和condition。

这里$ condition是一个类似的数组:

$condition = array(
        'id' => 'some id',
        'anycondition' => 'any value');

public function get($tbl_name, $condition = null) {
    if($condition) {
        $data = "select * from '$tbl_name' WHERE '$condition'";
    }
    else {
        $data = $tbl_name;
    }
    return $data;
}

我希望回声像这样

select * from $tbl_name WHERE id='some id' and anycondition='any value'

3 个答案:

答案 0 :(得分:0)

试试这个:

$query ="SELECT * FROM '$tbl_name' WHERE id='".$condition['id']."' AND anycondition='".$condition['anycondition']."'";

答案 1 :(得分:0)

$data="select * from '$tbl_name' WHERE 
(select array_to_string($condition, 'and', '') as condition);

here(在array_to_string中):

first parameter -->array

 2nd -->concatenation text

3rd -->replacement of the null value in your array

答案 2 :(得分:0)

这是一种处理应用程序数据库层的类的可怕方法。如果我是你,我会仔细阅读mysqli驱动程序http://us2.php.net/manual/en/book.mysqli.php并提出更好的解决方案。

但这是我认为你在开幕式上想要完成的事情。

class A
{
    public function sqlSelect($dbh, $tableName, $params=array()) {
        if (!empty($param)) {
            foreach ($params as $field => $value) {
                // http://www.php.net/manual/en/function.mysql-real-escape-string.php
                $value = mysql_real_escape_string($value, $dbh);
                $whereSql[] = sprintf("%s = %s", $field, $value); 
            }
            $whereSql = implode(" AND ", $whereSql);
            return sprintf("SELECT * FROM %s WHERE %s", 
                           $tableName, $whereSql);
        }
        return sprintf("SELECT * FROM %s", $tableName);
    }
}

$condition = array(
    'id' => 1234,
    'some_other_column' => 'someOtherValue'
);
echo A.sqlSelect('SomeTableName', $condition);
echo A.sqlSelect('SomeOtherTableName');

Output:
SELECT * FROM SomeTableName WHERE id = 1234 AND some_other_column = 'someOtherValue'
SELECT * FROM SomeOtherTableName