通过数组键和值以MySQL查询字符串 [英] Pass array keys and values to Mysql Query String

查看:121
本文介绍了通过数组键和值以MySQL查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经重新presents一个数组,其中我的SQL查询的WHERE子句。

I have an array represents WHERE clause of my SQL query.

$qWhere= array("cName" => "Turgay Metal", "cTelephone" => "5556162"); 

我的功能是:(简体)

my function is: (simplified)

<?php
function getAll($tableName,$qWhere="") {
$qWhere = $qWhere == "" ? $qWhere : (" WHERE " . $qWhere);  
$sql = "SELECT * FROM $tableName $qWhere";}

所以,我需要写另一个函数还挺序列化与的foreach 阵列 $ K ='$ V'然后再加入AND,然后返回字符串。最后提供串入主要功能:

So i need to write another function to kinda serialize array with foreach as $k = '$v' and then join " AND " then return the string. Finally supply the string into main function:

function arr2sql($qWhere) {
    foreach ($qWhere as $key=>$value) { $fields[] = sprintf("%s = '%s'", $key, secure($value));} 
    $field_list = join(' AND ', $fields); unset($qWhere);
    return $field_list;
}

这是正确的方式,也可以它可以实现更加干净profesionally?

Is this the correct way or may it be achieved more clean and profesionally?

感谢您的帮助。

推荐答案

我认为它看起来pretty好;我喜欢。我假设安全()免受SQL注入保护。我真的没有看到什么我会改变。

I think it looks pretty good; I like it. I assume secure() protects from sql injection. I don't really see anything I would change.

您的可能的括号取出来的用于自一个语句循​​环,但是这是没有biggy

You could take braces out of the for loop since its one statement, but that's no biggy

foreach ($qWhere as $key=>$value)
    $fields[] = sprintf("%s = '%s'", $key, secure($value));

这篇关于通过数组键和值以MySQL查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆