【问题标题】:Connecting to database via PHP and displaying contents on browser通过 PHP 连接数据库并在浏览器上显示内容
【发布时间】:2014-11-03 08:22:05
【问题描述】:

我正在通过 PHP 脚本连接到 SQL 服务器并在浏览器上显示检索到的内容。

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"
href="http://cdn.sencha.com/ext/trial/5.0.0/build/packages/ext-theme-neptune/build/resources/ext-    
theme-neptune-all.css">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/php" src="connection.php"></script>

</head>
<body>
</body>
</html>

app.js

document.addEventListener('DOMContentLoaded', function() {

    d3.json("connection.php", function (data) {
        document.write(data);
    });
});

连接.php

<?php

// Server Name
$myServer = "10.112.1.2";

// Database
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=>"logs", "CharacterSet"=>"UTF-8");

$conn = sqlsrv_connect($myServer, $connectionInfo);
if (!$conn) {
    $message = "Connection failed";
    echo "<script type='text/javascript'>alert('$message');</script>";
} else {
    $message = "Connected";
    echo "<script type='text/javascript'>alert('$message');</script>";
}

$sql = "SELECT * FROM dbo.logsData";
$data = sqlsrv_query( $conn, $sql );
if( $data === false ) {
    echo "Error in executing query.</br>";
    die( print_r( sqlsrv_errors(), true));
}

$result = array(); 

do {
    while ($row = sqlsrv_fetch_array($data, SQLSRV_FETCH_ASSOC)){
        $result[] = $row; 
    }
} while ( sqlsrv_next_result($data) );

echo json_encode($result);

sqlsrv_free_stmt($data);
sqlsrv_close($conn);
?>

所有 3 个文件都在同一个文件夹中。 浏览器只显示一个空值,我没有点击 .php 文件中的任何日志信息。我的方法对吗?我是否使用了正确的 javascript 事件?

【问题讨论】:

  • 将所有内容包装在 try/catch (php.net/manual/en/language.exceptions.php) 中,它会告诉您 php.ini 设置是否隐藏了一些错误。
  • 其他一切正常吗?如何单独测试连接?
  • 如果您只想检查与您的连接对象关联的值,请使用var_dump

标签: javascript php sql-server


【解决方案1】:

以这种方式更改您的connection.php:

    if (!$conn) {
    $message = "Connection failed";
    echo "<script type='text/javascript'>alert('$message');</script>";
} else {
    header('Content-Type: application/json');
}

您需要更改回复的 MIME 类型。此外,您不能打印除 json 数据之外的任何内容。这就是我从你的代码中删除这些行的方式:

    $message = "Connected";
    echo "<script type='text/javascript'>alert('$message');</script>";

【讨论】:

    【解决方案2】:

    尝试在此处为 connection.php 使用相对路径名:d3.json("connection.php"

    类似“/dirname/connection.php”的东西。

    您可以使用完整路径名单独测试 connection.php,例如 http://www.yourserver.xxx/dirname1/dirname2/...connection.php

    【讨论】:

    • 单独测试connection.php怎么样?
    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 2012-12-27
    • 2015-09-15
    • 2020-11-10
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多