用于将mysql数据转换为json的PHP脚本在执行时不会返回任何内容

时间:2016-09-17 19:10:28

标签: php mysql json mysqli

我试图从在线托管数据库中获取信息并将其转换为json,我有我制作的php脚本,但是当我执行它时,它会显示一个空白页面,它应该显示数据库中的数据。

这是脚本:

    <?php

define('HOST','---');
define('USER','---');
define('PASS','---');
// define('DB','plofenosa');
 
$con = mysqli_connect(HOST,USER,PASS);

if (!$con)
{
    die ('Could not connect:' .mysqli_connect_error());
}

mysqli_select_db("plofenosa", $con);

$result = mysqli_query("SELECT * FROM Obras");

while($row = mysqli_fetch_assoc($result)) 
{
    $output[]=$row;
}

print json_encode($output);

mysqli_close($con);

?>

更新:

    <?php

define('HOST','mssql3.gear.host');
define('USER','plofenosa');
define('PASS','Xn6g_1s_IqFc');
define('DB','plofenosa');
 
$con = mysqli_connect(HOST,USER,PASS);

if (!$con)
{
    die ('Could not connect:' .mysqli_connect_error());
}

 mysqli_select_db("plofenosa", $con);

$result = mysqli_query("SELECT * FROM Obras");
    $output = array(); //Added new line
    while($row = mysqli_fetch_assoc($result)) 
    {
        $output[]=$row;
    }

    print json_encode($output);


mysqli_close($con);

?>

更新#2

    <?php

$serverName = "---";

/* Get UID and PWD from application-specific files.  */
$uid = 'plofenosa';
$pwd = '---';
$connectionInfo = array( "UID"=>$uid,
                         "PWD"=>$pwd,
                         "Database"=>"plofenosa");

/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
     echo "Unable to connect.</br>";
     die( print_r( sqlsrv_errors(), true));
}

echo 'Connected successfully';

$tsql = "SELECT * FROM Obras";
$stmt = sqlsrv_query($conn, $tsql);

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

$json = array();

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

/* Run the tabular results through json_encode() */
/* And ensure numbers don't get cast to trings */
print json_encode($json,<code> JSON_NUMERIC_CHECK</code>);
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);

?>

2 个答案:

答案 0 :(得分:2)

此语法不正确

mysqli_select_db("plofenosa", $con);

应该是

mysqli_select_db($con, "plofenosa");

请注意,连接变量首先不是秒。

如果有疑问,您可以随时read the manual作为最后的手段

或者使用连接选择数据库可能更简单

$con = mysqli_connect(HOST,USER,PASS, "plofenosa");

See the manual for mysqli_connect

并完全删除mysqli_select_db()

答案 1 :(得分:0)

使用此代码

mysqli_select_db("plofenosa", $con);

    $result = mysqli_query("SELECT * FROM Obras");
    $output = array(); //Added new line
    while($row = mysqli_fetch_assoc($result)) 
    {
        $output[]=$row;
    }

    print json_encode($output);

    mysqli_close($con);