简体   繁体   中英

PDO - Iteratively Binding Variables

I am trying to create a function to iteratively bind variables. This is what I have so far:

function prepareQuery($db, $query, $args) {
    // Returns a prepared statement
    $stmt = $db->prepare($query);
    foreach ($args as $arg => $value) {
        $stmt->bindParam($arg, $value);
        }
    return $stmt;
    }

This is how I'm using it:

$stmt = prepareQuery($db, "SELECT * FROM `Licenses` WHERE `verCode`=:verCode", Array(":verCode" => $verCode));
$verCode = "some_string";
$stmt->execute();
while ($info = $stmt->fetch()) {
    print_r($info);
    }

Though it doesn't print anything. I know the database entry exists, and the same query works from PHPMyAdmin. So, I think it's just a problem in how my function tries to create the bindings. How can I fix this? Thanks!

  1. Do not create a function to iteratively bind variables. PDO can do it already

     function prepareQuery($db, $query, $args) { $stmt = $db->prepare($query); $stmt->execute($args); return $stmt; } 
  2. If it doesn't print anything, then it didn't find anything. As simple as that.

  3. You don't even need this prepare query function actually. Just amend PDO very little like this

     class myPDOStatement extends PDOStatement { function execute($data = array()) { parent::execute($data); return $this; } } $user = 'root'; $pass = ''; $dsn = 'mysql:charset=utf8;dbname=test;host=localhost'; $opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => TRUE, PDO::ATTR_STATEMENT_CLASS => array('myPDOStatement'), ); $pdo = new PDO($dsn, $user, $pass, $opt); 

and you'll be able to write such a neat chain:

$sql  = "SELECT * FROM `Licenses` WHERE `verCode`=:verCode";
$code = "some_string";
$data = $pdo->prepare($sql)->execute([$code])->fetchAll();
foreach ($data as $info) {
    print_r($info);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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