使用JSON的数据库连接

时间:2018-06-01 07:01:11

标签: php sql json sql-server

我的PHP代码,

<?php
 header("Content-Type: application/json; charset=UTF-8");
 $obj = json_decode($_GET["x"], false);
 $serverName = "AE58RETY245YU"; 
 $connectionInfo = array( "Database"=>"Test", "UID"=>"bala", 
 "PWD"=>"bala");
 $conn = sqlsrv_connect( $serverName, $connectionInfo);
 if( $conn ) {
 echo "Connection established.<br />";
 }else{
 echo "Connection could not be established.<br />";
 die( print_r( sqlsrv_errors(), true));
 }
 $outp=array();
 $sql = "SELECT Point FROM ".$obj->table."LIMIT".$obj->limit;
 $stmt = sqlsrv_query( $conn, $sql );
 while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
 $outp=$row['Point'];
 }
 echo json_encode($outp);
?>

我的HTML代码,

<!DOCTYPE html>
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p>The JSON received from the PHP file:</p>
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp;
obj = { "table":"PointEvent", "limit":10 }; 
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML = this.responseText;
}
};
 xmlhttp.open("GET", "testsql.php?x=" + dbParam, true);
 xmlhttp.send();

</script>

</body>
</html>

嗨,

上面是我的PHP和HTML代码,我尝试使用Json(Encode和Decode方法)连接sql数据库并尝试打印单列,但错误是

  

&#39;警告:sqlsrv_fetch_array()要求参数1为资源,在&#39;中给出布尔值。

任何人都可以帮我解决这个问题。

先谢谢。

2 个答案:

答案 0 :(得分:0)

我在您的查询“添加空间”中发现了连接问题,否则查询看起来像“SELECT Point FROM mytableLIMIT1

$sql = "SELECT Point FROM ".$obj->table."LIMIT".$obj->limit;

$sql = "SELECT Point FROM ".$obj->table." LIMIT ".$obj->limit;

通过在

之前添加行来正确处理异常
if( $stmt === false ) { /*!Handle exception here*/ }

看来你是编程新手。在使用数据库时,永远不要相信像$ _GET [“x”]这样的原始用户输入。做适当的清理,否则最终会在sql注入。

通过以下链接了解更多信息

What are the best PHP input sanitizing functions?

How can I prevent SQL injection in PHP?

答案 1 :(得分:0)

$stmt = sqlsrv_query($conn, $sql);语句的行可能会导致您的问题。我认为$sql形成不好。我不确定MS SQL Server是否有'LIMIT'个关键字,因此请先尝试使用$sql = "SELECT Point FROM ".$obj->table;

在使用sqlsrv_query()

之前,您还必须始终检查sqlsrv_fetch_array()结果
$sql = "SELECT Point FROM ".$obj->table;
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false ) {
    echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
    exit;
}
...