PHP 内爆关联数组

发布于 2024-09-10 12:51:10 字数 761 浏览 6 评论 0原文

所以我试图创建一个函数来生成基于多维数组的 SQL 查询字符串。

示例:

function createQueryString($arrayToSelect, $table, $conditionalArray) {
$queryStr = "SELECT ".implode(", ", $arrayToSelect)." FROM ".$table." WHERE ";
$queryStr = $queryStr.implode(" AND ",$conditionalArray); /*NEED HELP HERE*/
return $queryStr;
}

$columnsToSelect = array('ID','username');
$table = 'table';
$conditions = array('lastname'=>'doe','zipcode'=>'12345');
echo createQueryString($columnsToSelect, $table, $conditions); /*will result in incorrect SQL syntax*/

如您所见,我需要有关第三行的帮助,因为它当前正在打印

从表 WHERE 中选择 ID、用户名 姓氏和邮政编码

,但应该打印

从表 WHERE 中选择 ID、用户名 姓氏 = 'doe' AND 邮政编码 = '12345'

So I'm trying to create a function that generates a SQL query string based on a multi dimensional array.

Example:

function createQueryString($arrayToSelect, $table, $conditionalArray) {
$queryStr = "SELECT ".implode(", ", $arrayToSelect)." FROM ".$table." WHERE ";
$queryStr = $queryStr.implode(" AND ",$conditionalArray); /*NEED HELP HERE*/
return $queryStr;
}

$columnsToSelect = array('ID','username');
$table = 'table';
$conditions = array('lastname'=>'doe','zipcode'=>'12345');
echo createQueryString($columnsToSelect, $table, $conditions); /*will result in incorrect SQL syntax*/

as you can see I need help with the 3rd line as it's currently printing

SELECT ID, username FROM table WHERE
lastname AND zipcode

but it should be printing

SELECT ID, username FROM table WHERE
lastname = 'doe' AND zipcode = '12345'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

歌枕肩 2024-09-17 12:51:10

您实际上并没有内爆多维数组。 $conditions 是一个关联数组。

只需在函数 createQueryString() 中使用 foreach 循环即可。像这样的东西应该可以工作,注意它未经测试。:

$terms = count($conditionalArray);
foreach ($conditionalArray as $field => $value)
{
    $terms--;
    $queryStr .= $field . ' = ' . $value;
    if ($terms)
    {
        $queryStr .= ' AND ';
    }
}

注意:为了防止 SQL 注入,这些值应该根据所使用的数据库的适当/需要进行转义和/或引用。不要只是复制和粘贴;思考!

You're not actually imploding a multidimensional array. $conditions is an associative array.

Just use a foreach loop inside your function createQueryString(). Something like this should work, note it's untested.:

$terms = count($conditionalArray);
foreach ($conditionalArray as $field => $value)
{
    $terms--;
    $queryStr .= $field . ' = ' . $value;
    if ($terms)
    {
        $queryStr .= ' AND ';
    }
}

Note: To prevent SQL injection, the values should be escaped and/or quoted as appropriate/necessary for the DB employed. Don't just copy and paste; think!

江南月 2024-09-17 12:51:10
function implodeItem(&$item, $key) // Note the &$item
{
  $item = $key . "=" . $item;
}

[...]

$conditionals = array(
  "foo" => "bar"
);

array_walk($conditionals, "implodeItem");
implode(' AND ', $conditionals);

未经测试,但类似的东西应该可以工作。这样你还可以检查 $item 是否是一个数组,并在这些情况下使用 IN 。

function implodeItem(&$item, $key) // Note the &$item
{
  $item = $key . "=" . $item;
}

[...]

$conditionals = array(
  "foo" => "bar"
);

array_walk($conditionals, "implodeItem");
implode(' AND ', $conditionals);

Untested, but something like this should work. This way you can also check if $item is an array and use IN for those cases.

我的鱼塘能养鲲 2024-09-17 12:51:10

您必须编写另一个函数来处理 $conditionalArray,即处理 $key => $value 并处理类型,例如,如果它们是字符串,则应用引号。

您只是处理 = 条件吗? LIKE<> 怎么样?

You will have to write another function to process the $conditionalArray, i.e. processing the $key => $value and handling the types, e.g. applying quotes if they're string.

Are you just dealing with = condition? What about LIKE, <, >?

青巷忧颜 2024-09-17 12:51:10

如果不太性感请原谅我!

 $data = array('name'=>'xzy',
              'zip'=>'3432',
              'city'=>'NYK',
              'state'=>'Alaska');


$x=preg_replace('/^(.*)$/e', ' "$1=\'". $data["$1"]."\'" ',array_flip($data));

$x=implode(' AND ' , $x);

所以输出将是这样的:

 name='xzy' AND zip='3432' AND city='NYK' AND state='Alaska'

Forgive me if its not too sexy !

 $data = array('name'=>'xzy',
              'zip'=>'3432',
              'city'=>'NYK',
              'state'=>'Alaska');


$x=preg_replace('/^(.*)$/e', ' "$1=\'". $data["$1"]."\'" ',array_flip($data));

$x=implode(' AND ' , $x);

So the output will be sth like :

 name='xzy' AND zip='3432' AND city='NYK' AND state='Alaska'
萧瑟寒风 2024-09-17 12:51:10

我建议不要自动创建条件。
您的情况太本地化,而可能还有许多其他运算符 - LIKE、IN、BETWEEN、<、>等等
一些逻辑包括多个 AND 和 OR。

最好的方法是手动方式。
我总是以这种方式做这样的事情

if (!empty($_GET['rooms']))     $w[]="rooms='".mesc($_GET['rooms'])."'";
if (!empty($_GET['space']))     $w[]="space='".mesc($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mesc($_GET['max_price'])."'";

,但是如果您仍然想要使用这个简单的数组,只需使用它进行迭代

foreach ($conditions as $fieldname => $value)...

,然后以您需要的方式组合这些变量即可。你有两个选择:使用 field='value' 对创建另一个数组,然后将其内爆,或者只是连接起来,并在末尾添加 substr 尾随 AND

I'd advise against automated conditionals creation.
Your case is too local, while there can be many other operators - LIKE, IN, BETWEEN, <, > etc.
Some logic including several ANDs and ORs.

The best way is manual way.
I am always doing such things this way

if (!empty($_GET['rooms']))     $w[]="rooms='".mesc($_GET['rooms'])."'";
if (!empty($_GET['space']))     $w[]="space='".mesc($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mesc($_GET['max_price'])."'";

Though if you still want it with this simple array, just iterate it using

foreach ($conditions as $fieldname => $value)...

and then combine these variables in the way you need. you have 2 options: make another array of this with field='value' pairs and then implode it, or just concatenate, and substr trailing AND at the end.

信愁 2024-09-17 12:51:10

我使用了它的变体:

function implode_assoc($glue,$sep,$arr)
{
    if (empty($glue)) {$glue='; ';}
    if (empty($sep)) {$sep=' = ';}
    if (is_array($arr))
    {
        foreach ($arr as $k=>$v)
        {
            $str .= $k.$sep.$v.$glue;
        }
        return $str;
    } else {
        return false;
    }
};

它很粗糙但有效。

I use a variation of this:

function implode_assoc($glue,$sep,$arr)
{
    if (empty($glue)) {$glue='; ';}
    if (empty($sep)) {$sep=' = ';}
    if (is_array($arr))
    {
        foreach ($arr as $k=>$v)
        {
            $str .= $k.$sep.$v.$glue;
        }
        return $str;
    } else {
        return false;
    }
};

It's rough but works.

长发绾君心 2024-09-17 12:51:10

这是一个工作版本:

//use: implode_assoc($v,"="," / ")
//changed: argument order, when passing to function, and in function
//output: $_FILES array ... name=order_btn.jpg / type=image/jpeg / tmp_name=G:\wamp\tmp\phpBDC9.tmp / error=0 / size=0 / 

function implode_assoc($arr,$glue,$sep){
    $str = '';
    if (empty($glue)) {$glue='; ';}
    if (empty($sep)) {$sep=' = ';}
    if (is_array($arr))
    {
        foreach ($arr as $key=>$value)
        {
            $str .= $key.$glue.$value.$sep;
        }
        return $str;
    } else {
        return false;
    }
}

Here is a working version:

//use: implode_assoc($v,"="," / ")
//changed: argument order, when passing to function, and in function
//output: $_FILES array ... name=order_btn.jpg / type=image/jpeg / tmp_name=G:\wamp\tmp\phpBDC9.tmp / error=0 / size=0 / 

function implode_assoc($arr,$glue,$sep){
    $str = '';
    if (empty($glue)) {$glue='; ';}
    if (empty($sep)) {$sep=' = ';}
    if (is_array($arr))
    {
        foreach ($arr as $key=>$value)
        {
            $str .= $key.$glue.$value.$sep;
        }
        return $str;
    } else {
        return false;
    }
}
伴我老 2024-09-17 12:51:10

我知道这是针对 pdo mysql 类型的情况..但我所做的是构建 pdo 包装方法,在这种情况下,我执行此函数来帮助构建字符串,因为我们使用键,所以没有可能的方法mysql 注入,因为我知道我手动定义/接受的键。

想象一下这个数据:

           $data=array(
            "name"=>$_GET["name"],
            "email"=>$_GET["email"]
);

您定义了 utils 方法...

public static function serialize_type($obj,$mode){
$d2="";
if($mode=="insert"){
    $d2.=" (".implode(",",array_keys($obj)).") ";
    $d2.=" VALUES(";
foreach ($obj as $key=>$item){$d2.=":".$key.",";}
$d2=rtrim($d2,",").")";}

if($mode=="update"){
    foreach ($obj as $key=>$item){$d2.=$key."=:".$key.",";}    
}
return rtrim($d2,",");
}

然后查询绑定数组生成器(我可以使用直接数组引用,但让我们简化):

  public static function bind_build($array){
     $query_array=$array;
     foreach ($query_array as $key => $value) { $query_array[":".$key] =   $query_array[$key]; unset($query_array[$key]); } //auto prepair array for PDO
return $query_array;    }

然后您执行...

$query ="insert into table_x ".self::serialize_type( $data, "insert" );
$me->statement = @$me->dbh->prepare( $query ); 
$me->result=$me->statement->execute( self::bind_build($data) );

您也可以使用...轻松更新

  $query ="update table_x set ".self::serialize_type( $data, "update" )." where id=:id";
    $me->statement = @$me->dbh->prepare( $query ); 

    $data["id"]="123"; //add the id 
    $me->result=$me->statement->execute( self::bind_build($data) );

但是这里最重要的部分是serialize_type函数

I know this is for the case of a pdo mysql type.. but what i do is build pdo wrapper methods, and in this case i do this function that helps to build the string, since we work with keys, there is no possible way to mysql inject, since i know the keys i define / accept manually.

imagine this data:

           $data=array(
            "name"=>$_GET["name"],
            "email"=>$_GET["email"]
);

you defined utils methods...

public static function serialize_type($obj,$mode){
$d2="";
if($mode=="insert"){
    $d2.=" (".implode(",",array_keys($obj)).") ";
    $d2.=" VALUES(";
foreach ($obj as $key=>$item){$d2.=":".$key.",";}
$d2=rtrim($d2,",").")";}

if($mode=="update"){
    foreach ($obj as $key=>$item){$d2.=$key."=:".$key.",";}    
}
return rtrim($d2,",");
}

then the query bind array builder ( i could use direct array reference but lets simplify):

  public static function bind_build($array){
     $query_array=$array;
     foreach ($query_array as $key => $value) { $query_array[":".$key] =   $query_array[$key]; unset($query_array[$key]); } //auto prepair array for PDO
return $query_array;    }

then you execute...

$query ="insert into table_x ".self::serialize_type( $data, "insert" );
$me->statement = @$me->dbh->prepare( $query ); 
$me->result=$me->statement->execute( self::bind_build($data) );

You could also go for an update easy with...

  $query ="update table_x set ".self::serialize_type( $data, "update" )." where id=:id";
    $me->statement = @$me->dbh->prepare( $query ); 

    $data["id"]="123"; //add the id 
    $me->result=$me->statement->execute( self::bind_build($data) );

But the most important part here is the serialize_type function

故人如初 2024-09-17 12:51:10

试试这个

function GeraSQL($funcao, $tabela, $chave, $valor, $campos) {
    $SQL = '';

    if ($funcao == 'UPDATE') :
        //Formata SQL UPDATE

        $SQL  = "UPDATE $tabela SET ";
        foreach ($campos as $campo => $valor) :
            $SQL .= "$campo = '$valor', ";
        endforeach;
        $SQL  = substr($SQL, 0, -2);
        $SQL .= " WHERE $chave = '$valor' ";

    elseif ($funcao == 'INSERT') :
        //Formata SQL INSERT

        $SQL  = "INSERT INTO $tabela ";

        $SQL .= "(" . implode(", ", array_keys($campos) ) . ")";

        $SQL .= " VALUES ('" . implode("', '", $campos) . "')";         

    endif;

    return $SQL;
}

//Use
$data = array('NAME' => 'JOHN', 'EMAIL' => '[email protected]');
GeraSQL('INSERT', 'Customers', 'CustID', 1000, $data);

Try this

function GeraSQL($funcao, $tabela, $chave, $valor, $campos) {
    $SQL = '';

    if ($funcao == 'UPDATE') :
        //Formata SQL UPDATE

        $SQL  = "UPDATE $tabela SET ";
        foreach ($campos as $campo => $valor) :
            $SQL .= "$campo = '$valor', ";
        endforeach;
        $SQL  = substr($SQL, 0, -2);
        $SQL .= " WHERE $chave = '$valor' ";

    elseif ($funcao == 'INSERT') :
        //Formata SQL INSERT

        $SQL  = "INSERT INTO $tabela ";

        $SQL .= "(" . implode(", ", array_keys($campos) ) . ")";

        $SQL .= " VALUES ('" . implode("', '", $campos) . "')";         

    endif;

    return $SQL;
}

//Use
$data = array('NAME' => 'JOHN', 'EMAIL' => '[email protected]');
GeraSQL('INSERT', 'Customers', 'CustID', 1000, $data);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文