无法对数据库执行查询

问题描述:

I am getting

Invalid query An attempt was made to access a socket in a way forbidden by its access permissions error

I am trying to connect to my azure sql server using php. I have the following code:

    $serverName = "cosy.database.windows.net, 1433"; //serverName\instanceName
    $connectionInfo = array( "Database"=>"cosy", "UID"=>"eocribin", "PWD"=>"password");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Connection established.<br />";

     $query = sprintf("SELECT username FROM Users 
    WHERE username=eoin");
    $result = mysql_query($query);

        echo $result;

    // Check result
    // This shows the actual query sent to MySQL, and the error. Useful for debugging.
    if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "
";
    $message .= 'Whole query: ' . $query;
    die($message);
}

Not sure if it's problem with the query or the actual permissions to the database but I do get connection successful followed by the error so I know it is connection.

It seems that you attempted to connect to Azure SQL Server, but you used mysql_query($query) in your code.

To query in SQLServer, you can refer to http://php.net/manual/zh/function.sqlsrv-fetch-array.php.

And here is the code snippet:

if ($conn) {
    echo "Connection established.<br />";

    $query = sprintf("SELECT 1 as test");
    $stmt = sqlsrv_query($conn, $query);
    if ($stmt === false) {
        die(print_r(sqlsrv_errors(), true));
    }

    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        print_r($row);
    }

    sqlsrv_free_stmt($stmt);

}