PHP使用Sqlsrv_query从SQL Server获取记录

时间:2016-08-20 16:34:16

标签: php sql-server sqlsrv

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

  

注意:未定义的变量:第24行的C:\ xampp \ htdocs \ kekportal \ test1.php中的员工

     

注意:未定义的变量:第28行的C:\ xampp \ htdocs \ kekportal \ test1.php中的员工

     

注意:未定义的变量:第28行的C:\ xampp \ htdocs \ kekportal \ test1.php中的员工

我的代码:

$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'];
}   

1 个答案:

答案 0 :(得分:2)

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

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

此外,您还可以使用其他代码来使用SQL Server。

$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