【问题标题】:Associative arrays and binding parameters关联数组和绑定参数
【发布时间】:2009-04-12 17:58:39
【问题描述】:

我对@9​​87654321@ 函数有点困惑。

我有这样的事情

array('user_email'=>'hello@net.com','user_pass'=>'password')

我想把它翻译成这样的东西

INSERT INTO user_info (user_email, user_pass) VALUES (hello@net.com, password)

使用带有 PDO 的参数化查询(或 mysqli,我愿意接受建议)。 另一个想法 -

array('uid'=>'10', 'first_name'=>'robert', 'last_name'=>'jones')
array("email", "number")

进入

SELECT email, number FROM t1 WHERE uid=10 AND first_name=robert AND last_name=jones

我知道答案在 PDO::preparecall_user_func_array 的某个地方,但我对后一个函数的工作原理感到非常困惑,希望得到解释。

【问题讨论】:

    标签: php pdo mysqli


    【解决方案1】:

    我很困惑,也许你也是。这是一个简单的例子:

    $sth = $dbh->prepare('SELECT * FROM table WHERE id = ? AND date = ?');
    $sth->execute(array(150, '2009-04-04'));
    $data = $sth->fetchAll();
    

    或者:

    $sth = $dbh->prepare("INSERT table VALUES(:foo, :bar)");
    $sth->bindParam(":foo", $foo);
    $sth->bindParam(":bar", $bar);
    

    或者:

    $sth = $dbh->prepare("INSERT INTO user_info (user_email, user_pass) VALUES (:email, :pass)");
    $sth->execute(array(':email' => 'foo@example.org', ':pass' => '1234'));
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      PDOStatement::execute() 与参数标记一起使用,因此您必须在调用 PDO::prepare() 之前构造查询。

      【讨论】:

        【解决方案3】:

        您不必使用 call_user_func_array()。 PDOStatement::execute() 默认采用关联数组。

        $stmt = $pdo->prepare("SELECT fld FROM tbl WHERE fld=:parameter1 AND fld2=:parameter2");
        $stmt->execute(array(":parameter1" => "value1", ":parameter2" => "value2"));
        ...
        

        http://se.php.net/manual/en/pdo.prepare.php

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-02-23
          • 1970-01-01
          • 2017-09-02
          • 2018-02-06
          • 1970-01-01
          • 2014-06-20
          • 2013-06-06
          • 1970-01-01
          相关资源
          最近更新 更多