我正在开发一个与SQL Server后端交互的PHP网站。它可能工作一次,然后当我尝试重新登录时(需要与SQL数据库通信),我得到了这个:
Fatal error: Invalid handle returned. in .... / sqlWorker.php on line 18
连接字符串错误似乎是最明显的罪魁祸首;然而,正如我所说,它确实似乎连接一次,然后打破。问题可能是什么?感谢。
sqlWorker.php
<?php
class sqlWorker {
var $user;
var $pass;
var $host;
var $db;
var $conn;
function __construct($hostname, $dbName, $username, $password) {
$this->db = $dbName;
$this->host = $hostname;
$this->user = $username;
$this->pass = $password;
}
public function connect() {
try {
// this is the "Fatal error" line $conn = new PDO("sqlsrv:Server=$this->host;Database=$this->db", $this->user, $this->pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Database connection failure: " . $e->getMessage();
}
return $conn;
}
&#34;登录&#34;逻辑
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
function formatInput($data) {
$data = trim($data);
$data = strip_tags($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function alphabetizeResources($a, $b) {
if ($a->name == $b->name) {
return 0;
}
return ($a->name < $b->name) ? -1 : 1;
}
// define constants
define("HOST", "INSTANCE\INSTANCE");
define("DB", "DB");
define("USER", "USER");
define("PASS", "PASS");
define("ROOT", "/new/");
define("IMAGEPATH", ROOT . "includes/img");
define("STYLEPATH", ROOT . "includes/styles/");
define("SCRIPTPATH", ROOT . "includes/scripts/");
// necessary classes
include_once("sqlWorker.php");
include_once("imageManipulator.php");
include_once("entities.php");
include_once("cms.php");
// start session if it does not already exist
if (!isset($_SESSION)) {
session_start();
}
$isTeam = strpos(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), "/teammember");
$isHotel = strpos(parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), "/hotel");
$isAdmin = ( (isset($_SESSION['userLevel']) && $_SESSION['userLevel'] == 1) ? true : false );
// create instance of "helper" classes for database access and displaying HTML
$dbm = new sqlWorker(HOST, DB, USER, PASS);
$cmsInstance = new cms();
// user is attempting to login
if (isset($_POST['login'])) {
$error;
$username = formatInput($_POST["user"]);
$pass = formatInput($_POST["pass"]);
if ($dbm->getUser($username, $pass) != false) {
$_SESSION["userLevel"] = $dbm->getUser($username, $pass);
if ($dbm->getUser($username, $pass) != 1) {
header("Location: " . ROOT . "teammember/index.php");
} else {
header("Location: " . ROOT . "teammember/index.php");
}
} else {
$error = true;
}
}
非常感谢您的帮助。
答案 0 :(得分:1)
这种情况很可能是由connection pooling引起的。
对于PHP和连接池的某些版本的SQL Server驱动程序存在一些问题,因此请确保使用latest drivers
这实际上应该可以解决您的问题。如果没有,您可以暂时禁用连接池,如下所示:
$conn = new PDO("sqlsrv:Server=$this->host;Database=$this->db;ConnectionPooling=0", $this->user, $this->pass);
答案 1 :(得分:0)
我认为情况可能与西蒙提到的情况类似。我之前从未见过这个问题,但是能够通过重启Apache来解决这个问题。我怀疑它刷新了它(PDO驱动程序)可能已打开的所有连接。