mauzilla
mauzilla

Reputation: 3592

Struggling with prepared statements

I am unable to get the following working. I want to use prepared statements in the example below, but I am getting an error. The function defnitily gets passed the correct value in $array:

  private function getInfoFromSystem($array) {
        try {
            $sql = "
                SELECT     
                    PCO_AGENT.NAME, 
                    PCO_INBOUNDLOG.LOGIN AS LOGINID, 
                    PCO_INBOUNDLOG.PHONE AS CALLERID, 
                    PCO_INBOUNDLOG.STATION AS EXTEN, 
                    PCO_INBOUNDLOG.TALKTIME AS CALLLENGTH, 
                    PCO_INBOUNDLOG.CHANNELRECORDID AS RECORDINGID, 
                    PCO_SOFTPHONECALLLOG.RDATE, 
                    PCO_INBOUNDLOG.RDATE AS INBOUNDDATE
                FROM         
                    PCO_INBOUNDLOG 
                INNER JOIN
                      PCO_LOGINAGENT ON PCO_INBOUNDLOG.LOGIN = PCO_LOGINAGENT.LOGIN 
                INNER JOIN
                      PCO_SOFTPHONECALLLOG ON PCO_INBOUNDLOG.ID = PCO_SOFTPHONECALLLOG.CONTACTID 
                INNER JOIN
                      PCO_AGENT ON PCO_LOGINAGENT.AGENTID = PCO_AGENT.ID
                WHERE
                    LOGINID = :extension
            ";
            $arr = array(":extension" => $array['extension']);
            $query = $this->mssql->prepare($sql);
            $query->execute($arr);
           // $sql = "select * from sys.messages where message_id = 229";
            foreach($this->mssql->query($sql) as $row) {

                echo "<pre>";
                print_r($row);
                echo "</pre>";
            }

        }
        catch(PDOException $e) {
            echo $e->getMessage();
        }
}

Upvotes: 1

Views: 1210

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270765

You should not be calling query() after execute(). Instead you need to fetch() your rows:

$query = $this->mssql->prepare($sql);
$query->execute($arr);

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
  echo "<pre>";
  print_r($row);
  echo "</pre>";
}

// OR rather than the fetch loop above, use fetchAll()
$rowset = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($rowset);

In my experience with PDO + MSSQL, attempting to call a regular query immediately after calling execute() on a statement that returns rows will fail unless you have called $query->closeCursor() first. However, in this case, you should not be calling query() at all. You've already executed your statement with bound params, and just need to fetch rows from it.

Upvotes: 1

Related Questions