SQLSTATE[HY000]常规SQL Server错误:检查来自SQL Server的消息.(严重程度5)


SQLSTATE[HY000] General SQL Server error: Check messages from the SQL Server. (severity 5)

我遇到了这个错误,并尝试了各种跨栈流量和互联网网站的解决方案,但都无济于事。我被卡住了,因为我无论如何都想不出如何解决它。

这是我生成上述错误的代码。

<?php
session_start();
$name = $_REQUEST['name'];
require 'config.php';
try {
    $db = new PDO($dsn, $username, $password);
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $sth = $db->query("SELECT * FROM locations where name = '$name'");
    $locations = $sth->fetchAll();
     echo json_encode( $locations );
} catch (Exception $e) {
    echo $e->getMessage();
}
//header("Location: index.html?platemobnum=$platemobnum");

config.php

<?php
 $server     = "XXXXX";
 $username   = "XXX";
 $password   = "XXXXX";
 $database   = "Database";
 $dsn        = "mssql:host=$server;dbname=$database";

假设您的Web服务器可以与数据库服务器通信并且凭据正确,则以下代码将有效。它使用PDOStatement来防止SQL注入。

session_start();
require 'config.php';
try {
    // create a new connection (verify that your web server can communicate with db server and validate credentials)
    $db = new PDO( $dsn, $username, $password );
    // prepare a statement to prevent SQL injections
    $stmt = $db->prepare( "SELECT * FROM locations WHERE name = ?" );
    /* populate the arguments in your prepared statement.
       needs to be an array even though there is only one argument. */
    $stmt->execute( array( $_REQUEST['name'] ) );
    // fetch all results
    $locations = $stmt->fetchAll();
    // encode as JSON
    echo json_encode( $locations );
} catch (Exception $e) {
    echo $e->getMessage();
}