Jump to content

PDO statement: Setting execute variables


cunoodle2

Recommended Posts

Is there a way to pass more than one variable via the pdo execute statement (for example like in an array)?  I'm just trying to cut down the number of lines of code.  Right now I have...

 

<?php
//prepare SQL query using pdo statement
$stmt = $read->prepare("SELECT * FROM users where name = :name AND password = :pass");
$stmt->bindParam(':name', $username);
$stmt->bindParam(':pass', $pass);
$user_info = $stmt->execute();
print_r($user_info);
?>

 

Is it possible to do something like this??

<?php
//prepare SQL query using pdo statement
$stmt = $read->prepare("SELECT * FROM users where name = ? AND password = ?");
$user_info = $stmt->execute(array($username, $pass))->fetch();
print_r($user_info);
?>

 

I'd love to be able to execute, pass and fetch all at once to cut down on lines of code.

Link to comment
https://forums.phpfreaks.com/topic/97677-pdo-statement-setting-execute-variables/
Share on other sites

Why not just write yourself a function? I'm not too familiar with PDO, but from your code example, I would do:

 

<?php
  function doPdoExec($cnx,$qry,$data = null){
    $stmt = $cnx->prepare($qry);
    if(is_array($data) && count($data)){
      foreach($data as $key=>$val)
        $stmt->bindParam($key,$val);
    }
    return $stmt->execute();
  }

  //Usage
  $user_info = doPdoExec($read,"SELECT * FROM users where name = :name AND password = :pass",array(
    ':name' => $username,
    ':pass' => $pass,
  ));
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.