SQLSTATE [42000]:[Microsoft] [SQL Server的ODBC驱动程序13] [SQL Server]'`'附近的语法不正确

时间:2018-01-26 02:03:11

标签: php sql-server-2008 pdo

我使用PDO sqlsrv在SQL Server 2008上使用PHP 7,我为此插入创建了一个函数:

  public function insert($table, $values,$error_msg = "Error executing query."){
                try {

                    $vals = array($values);
                    $fieldnames = array_keys($vals[0]);
                    $sql = "INSERT INTO ".$table;

                    foreach ($fieldnames as $key => $value1) {
                        $fieldnames[$key] = '`'.$value1.'`';
                    }
                    $fields = "( ".implode(" ,", $fieldnames)." )";
                    $bound = "(:" .implode(", :", str_replace('`', '', $fieldnames))." )";
                    $sql .= $fields." VALUES ".$bound;
                    $this->query = $this->conn->prepare($sql);
                    $error_msg=$sql.json_encode($vals);
                    foreach ($vals as $val) {
                        $this->query->execute($val) or die('Error Code: '.$error_msg);
                        $this->rowcount=$this->query->rowCount();
                    }

                } catch (PDOException $e) {
                   echo ('There was a problem with inserting to database: ' .$e->getMessage());
                }
    }

但是当我这样称呼这个函数时:

        $sql = array('ppic_mo' => $manufacturing_order_no,
               'work_area' => $work_area,
               'item_number' => $item_number,
               'item_description' => $item_description,
               'machine_no' => $machine_no,
               'quantity' => $quantity,
               'material_required' => $material_required,
               'date_from' => $date_from,
               'date_to' => $date_to        
        );
        $conn->insert('ppic_ps',$sql,"0125181711");

我收到了这个错误:

  

插入数据库时​​出现问题:SQLSTATE [42000]:[Microsoft] [SQL Server的ODBC驱动程序13] [SQL Server]'`'附近的语法不正确。

我尝试使用这样的原生插入,它完全正常。

  $query = "INSERT INTO ppic_ps(ppic_mo,work_area,item_number,item_description,machine_no,quantity,material_required,date_from,date_to) VALUES (?,?,?,?,?,?,?,?,?)";
      $stmt = $this->conn->prepare($query);
      $stmt->bindParam(1,$manufacturing_order_no);
      $stmt->bindParam(2,$work_area);
      $stmt->bindParam(3, $item_number);
      $stmt->bindParam(4, $item_description);
      $stmt->bindParam(5,$machine_no);
      $stmt->bindParam(6,$quantity);
      $stmt->bindParam(7, $material_required);
      $stmt->bindParam(8,$date_from);
      $stmt->bindParam(9, $date_to);
      $stmt->execute();

任何想法为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

我已经通过消除

中的`来解决这个问题
foreach ($fieldnames as $key => $value1) {
       $fieldnames[$key] = '`'.$value1.'`';
}

因为当字段有“但MySql”时,sql server不执行查询。例如,在MySql中运行此查询:

INSERT INTO tablename(`field1`,`field2`) VALUES(?,?)

但是在SQL Server 2008中并没有运行。