PHP 使用 Sqlsrv_query 从 SQL 服务器获取记录

PHP getting records from SQL server using Sqlsrv_query

我有一个名为 dbo.[DATABASE$Employee] 的数据库 table,我想从 table 中获取记录,但我收到一条错误消息

Notice: Undefined variable: Employee in C:\xampp\htdocs\kekportal\test1.php on line 24

Notice: Undefined variable: Employee in C:\xampp\htdocs\kekportal\test1.php on line 28

Notice: Undefined variable: Employee in C:\xampp\htdocs\kekportal\test1.php on line 28

我的代码:

$pdo = new PDO("sqlsrv: Server=U4BUO1D;Database=AmanfoHR","**","**");
$stmt = $pdo->prepare("SELECT
dbo.[DATABASE$Employee].No_ AS empID,
dbo.[DATABASEG$Employee].[First Name] AS fname
FROM
dbo.[DATABASE$Employee]");
$stmt->execute(); 
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    echo $row['fname'];
}   

我猜 prepare 语句将 $Employee 作为变量,而这个变量没有定义。更改您的查询部分:

$stmt = $pdo->prepare("SELECT
e.No_ AS empID,
e.[First Name] AS fname
FROM
dbo.[DATABASE"."$"."Employee] e");

您也可以使用其他代码来使用 SQL 服务器。

$serverName = "U4BUO1D";
$connectionInfo = array("Database"=>"AmanfoHR", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

$tsql = "
SELECT  No_ AS empID,
        [First Name] AS fname
FROM dbo.[DATABASE"."$"."Employee];";

$stmt = sqlsrv_query( $conn, $tsql);

if( $stmt === false ) {
    echo "Error in executing query.</br>";
    die( print_r( sqlsrv_errors(), true));
}

while ($obj = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    echo $obj['fname'];
}

sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

您需要在 php.ini 中启用这两个扩展程序:

extension=php_pdo_sqlsrv.dll
extension=php_sqlsrv.dll