Question

I would like to setup an array with multiple parameters in it, pass it to my database class. Currently I can only send one parameter, but generally my sql queries have multiple parameters.

Sample database method:

public function fetchQuery($sql,$params,$conn){
    try{
        $queryparams=array($params);
        $x=$conn->prepare($sql);
        $x->execute($queryparams);
        $rArray = $x->fetchAll(PDO::FETCH_ASSOC);
        return $rArray;
    }catch (Exception $e){
        die( print_r( $e->getMessage() ) );
    }
}

Call to database method:

        $params=$vendID;
        $sql = "SELECT Email from Contact WHERE VendID = ?";

 try{
          $emails=$db->fetchQuery($sql,$params,$conn);
          $eCount = count($emails);
           if($eCount>0){
                foreach($emails as $row){
                    $eArray[]=$row['Email'];
                }
            }else{
                echo "No email addresses associated with this vendor";
            }
        }
        catch(Exception $e){
            die( print_r( $e->getMessage() ) );
        }

Now say my sql query was like: "Select * from Contact where CustID=? and Expired=?" How would I build an array and pass the into my function?

Every time I try, I get an array to string conversion error.

Thanks

Was it helpful?

Solution

Now say my sql query was like: "Select * from Contact where CustID=? and Expired=?" How would I build an array and pass the into my function?

I would remove the $queryparams=array($params); part of your code, and always pass the function an array even if it has only one elements.

$params= array($custID);
$sql = "SELECT Email from Contact WHERE VendID = ?";

try{
    $emails=$db->fetchQuery($sql,$params,$conn);

mutiple

$params= array($vendID, $expired);
$sql = "Select * from Contact where CustID=? and Expired=?";

try{
    $emails=$db->fetchQuery($sql,$params,$conn);

I personaly prefer the named parameter, where I can use the associative arrays:

$sql = "Select * from Contact where CustID= :custId and Expired= :expired";

$params= array(':custId'=>$custID, 
               ':expired'=>$expired
);

OTHER TIPS

In your fetchQuery method you can check if $params is already an array or not.

<?php
if (is_array($params)) {
    $queryParams = $params;
}
else {
    $queryParams = array($params);
}

You don't actually need this function. it saves you typing of just a couple words.
Yet the same time it is limiting you in using PDO. Look at your code with raw pdo

$stmt = $con->prepare("SELECT Email from Contact WHERE VendID = ?");
$stmt->execute([$vendID]);
$emails = $stmt->fetchAll(PDO::FETCH_COLUMN);
if(!$emails){
    echo "No email addresses associated with this vendor";
}

it's 3 times shorter than with your function.
PDO already is a wrapper by itself. One need VERY strong reasons and too much experience to be able to extend it proficiently.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top