Error in sqlsrv_fetch_array from PHP to SQL Server

3

In a connection from PHP to SQL server I have the following error:

  

sqlsrv_fetch_array () expects parameter 1 to be resource string given

This is the code:

$server = "SQLSERVER\INSTANCIAALABD";
$conn = array("Database" => "NOMBREDATABASE", "UID" => "NAME", "PWD" => "NAMEPWD");
$con  = sqlsrv_connect($server, $conn);

if($con){   
    echo "conectado";
} else {
    echo "desconectado";
}

$tsql = "select NOMBRE from CIUDAD";
$getciudad = sqlsrv_query($con, $tsql);
if($getciudad = FALSE) die(FormatErrors(sqlsrv_errors()));

while($row = sqlsrv_fetch_array($getciudad, SQLSRV_FETCH_ASSOC)){
    echo $row['NOMBRE'];
    echo "<br/>";
}
    
asked by alejza 11.05.2018 в 22:04
source

1 answer

1

To respond to your concern, follow the following:

        $server = "SQLSERVER\INSTANCIAALABD";
        $conn = array("Database" => "NOMBREDATABASE", "UID" => "NAME", "PWD" => "NAMEPWD");
        $con  = sqlsrv_connect($server, $conn);

    /*
    en lugar de validar solo con un echo 
    de conectado valida con el err sql que te 
    genera el dbms cuando hace cx...


        if($con){   
          //echo "conectado";

        } else {
            echo "desconectado";
        }
    */
    if( $con === false ) {
        die( print_r( sqlsrv_errors(), true));
    }

        $tsql = "select NOMBRE from CIUDAD";

        $getciudad = sqlsrv_query($con, $tsql);
    /*
    En este punto es importante identar para que tu consulta sea legible...
    a la vez que validas que tu consulta retorne diferente a false antes
    de iterar con tu bucle...
        if($getciudad = FALSE) die(FormatErrors(sqlsrv_errors()));
    */

    if( $getciudad === false) {
        die( print_r( sqlsrv_errors(), true) );
    }

        while($row = sqlsrv_fetch_array($getciudad, SQLSRV_FETCH_ASSOC)){
            echo $row['NOMBRE'];
            echo "<br/>";
        }

Keep in mind that the errors generated by the idea is to debug them and based on this you give a solution because it can be for your weapons, your query, driver ... n number of situations, with the errors you are going to to be able to know what really happens in the logic of your script ..

    
answered by 11.05.2018 в 22:40