简体   繁体   中英

How to call a stored procedure in SQL Server with parameters from PHP

I use Codeigniter and this is how I call a stored procedure in MySQL:

public function InsertDataSistra($NumPart, $typeChild){
    $sql = $this->db->query("CALL PYCC_InsertDataSistra('$NumPart', '$typeChild')");
}

But I need to call a stored procedure with parameters in SQL Server. My SP in SQL server is:

CREATE PROCEDURE CantidadReal_PRMS 
    @NumPart VARCHAR(25) = NULL, 
    @HOUSE VARCHAR(15) = NULL,
    @LBAIS FLOAT(45) = NULL, 
    @LBROW FLOAT(45) = NULL,
    @LBTIR FLOAT(45) = NULL
...

So what would be the call of this SP?

public function PzRealesPRMS($NumPart, $House, $LBAIS, $LBROW, $LBTIR){
    $sql = $this->db->query("EXEC CantidadReal_PRMS  ???????????????");
}

Injecting values in an SQL statement makes your approach wide open to possible SQL injection. What you may try is to use query bindings or prepared queries. In both cases, the Query Builder and Database connections handle escaping the data:

Statement using query bindings:

public function PzRealesPRMS($NumPart, $House, $LBAIS, $LBROW, $LBTIR) {
    $sql = $this->db->query(
       "EXEC CantidadReal_PRMS @NumPart = ?, @HOUSE = ?, @LBAIS = ?, @LBROW = ?, @LBTIR = ?",
       [$NumPart, $House, $LBAIS, $LBROW, $LBTIR]
    );
}

Statement using prepared query:

public function PzRealesPRMS($NumPart, $House, $LBAIS, $LBROW, $LBTIR) {
   $query = $this->db->prepare(function($db) {
      $sql = "EXEC CantidadReal_PRMS @NumPart = ?, @HOUSE = ?, @LBAIS = ?, @LBROW = ?, @LBTIR = ?";
      return (new Query($db))->setQuery($sql);
   });

   $results = $query->execute($NumPart, $House, $LBAIS, $LBROW, $LBTIR);
}

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