繁体   English   中英

将Array的内容添加到SQL查询中的where条件

[英]Adding content of Array into where Condition in SQL query

我试图使此函数get()带有tbl_name和将在WHERE中使用的条件。

这里$ 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'

尝试这个:

$query ="SELECT * FROM '$tbl_name' WHERE id='".$condition['id']."' AND anycondition='".$condition['anycondition']."'";
$data="select * from '$tbl_name' WHERE 
(select array_to_string($condition, 'and', '') as condition);

此处(在array_to_string中):

first parameter -->array

 2nd -->concatenation text

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

这是一种处理类的可怕方法,该类处理应用程序的数据库层。 如果您是我,我会通读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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM