将PDO与SQLServer连接

时间:2018-12-02 05:52:42

标签: php sql-server pdo

我正在尝试与PDOPHP MVC建立新的SQL Server连接,但是当我尝试咨询数据库时,会向我发送错误消息

Fatal error</b>:  Uncaught Error: Call to a member function prepare() on null

我正在尝试以此连接

<?php

class Conexion{

  static public function conectar(){

    $DATABASE="Database";
    $DB_USER="DBUser";
    $DB_PASSWORD="DBPassword";
    $SERVER_NAME = "ServerName";
    try
    {
      $db = new PDO("sqlsrv:Server=$SERVER_NAME;Database=$DATABASE", "$DB_USER", "$DB_PASSWORD");
      $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    }catch(PDOException $e){
      echo 'ERROR TO CONNECT' . $e->getMessage();
      die();
    }

  }

}

在另一个控制器中,我以此进行查询

    <?php

require_once "conexion.php";

class UserModel{

    static public function mdlSearchUser($table, $data){
      $stmt = Conexion::conectar() -> prepare("SELECT CB_CODIGO FROM $table WHERE CB_ACTIVO='S' AND CB_Codigo = $data");
      $stmt->execute();
      return $stmt -> fetchAll();
      $stmt ->close();
      $stmt = null;
    }
}

1 个答案:

答案 0 :(得分:0)

您需要返回一个PDO实例,该实例表示与请求的数据库的连接。您可以尝试更改sum(input)并在成功时返回conexion.php或在错误时返回return $db;的PDO实例:

return false;

并像这样使用<?php class Conexion { static public function conectar() { $DATABASE = "tornado_tmp"; $DB_USER = "tornado"; $DB_PASSWORD = "1234"; $SERVER_NAME = "127.0.0.1\ikosoft,1066"; try { $db = new PDO("sqlsrv:Server=$SERVER_NAME;Database=$DATABASE", "$DB_USER", "$DB_PASSWORD"); $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); return $db; } catch(PDOException $e) { echo 'ERROR TO CONNECT' . $e->getMessage(); return false; } } } ?> 类:

Conexion