用于连接数组和字符串的PHP方法

时间:2011-03-22 16:50:10

标签: php arrays string methods

我正在构建一个PHP类来处理数据库管理,我想知道是否有可能构建一个方法来接收带有连接数组的字符串作为一个变量。

例如,看看这个简化的代码:

class Database {
    function __construct() {
        // Connect to the database, code not shown
    }

    public function query($input) {
        // Do something with the input so the string values are recognized ...
        // and the array and its keys are converted into an SQL string.
        // Code not shown...

        mysql_query($processedInput);
        return true;
    }
}

所以,理想情况下,如果我运行这样的东西......

$db = new Database();
$db->query("UPDATE `table` SET " . 
            array("id" = "2",
                  "position" = "1",
                  "visible" = "1",
                  "name" = "My Name's John",
                  "description" = "This is neat!"
            ) . " WHERE `id` = '1'");

... PHP将生成,然后运行此SQL ...

mysql_query("UPDATE `table` SET `id` = '2', `position` = '1', `visible` = '1', 
`name` = 'My Name\'s John', `description` = 'This is neat!' WHERE `id` = '1'");

我可以完成所有细节的数组转换,但是,就目前而言,我只需要一种方法让PHP将输入分解为字符串和数组,然后单独评估它们。

喜欢避免将多个值传递给方法。

2 个答案:

答案 0 :(得分:1)

在Ruby中你可以做到这一点,但你在PHP中运气不好。好消息是,您可以稍微修改您正在做的事情,将查询和参数分别作为查询方法的参数传递:

$db->query("UPDATE `table` SET ? WHERE `id` = '1'", array(
  "id" = "2",
  "position" = "1",
  "visible" = "1",
  "name" = "My Name's John",
  "description" = "This is neat!"
);

然后在Database对象中处理插值和连接:

class Database {
    function __construct() {
        // Connect to the database, code not shown
    }

    public function query($query, $input) {
        $sql = $this->_normalize_query($query, $input)

        mysql_query($sql);
        return true;
    }

    protected function _normalize_query($query, $input) {
      $params = "";
      foreach($input as $k => $v) {
        // escape and assemble the input into SQL
      }
      return preg_replace('/\?/', $params, $query, 1);
    }
}

然而

已经有很多ORM非常有能力。如果您正在寻找组装查询而不管理结果的东西,您也可以找到一些东西。看起来你在这里不必要地重新发明轮子。

Good PHP ORM Library?

答案 1 :(得分:1)

您可以编写一种Helper函数,它们的工作方式如下:

(在class Database {内)

public function ArrayValues($array)
{
    $string = "";

    foreach($array as $Key => $Value)
    {
        $string .= "`$Key` = '$Value' ,";
    }
    // Get rid of the trailing ,

    // Prevent any weird problems
    if(strlen($string) > 1)
    {
        $string = substr($string, 0, strlen($string) - 2);
    }

    return $string;
}

然后你就像使用它一样:

$db->query("UPDATE `table` SET " . 
            $db->ArrayValues(array("id" = "2",
                  "position" = "1",
                  "visible" = "1",
                  "name" = "My Name's John",
                  "description" = "This is neat!"
            )) . " WHERE `id` = '1'");

我没有对此进行测试,但它应该可以正常工作。