Warnin of sqlsrv_fetch_array () expects parameter 1 to be resource

3

I'm going to the point, I'm doing a search engine and when I put certain names or data, the results are shown, the problem is with some others where nothing is shown and it shows me the following warning

  

Warning: sqlsrv_fetch_array () expects parameter 1 to be resource,   boolean given in

and I still do not know how the error is solved, I pass the part where the error marks me.

Here my code:

<?php
//USAR dicc.php para cambiar usuario pass y DB
error_reporting(-1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('max_execution_time', 300);
function dd($attr){
    print_r($attr);
    echo "-----<br>";
    var_dump($attr);
    echo "-----<br>";
    echo serialize($attr);
    die();
}
$logFile = "querys.log";
function creaWhere($attr, $cols){
    $tmp = ""; // variable temporal para sacar los wheres de la query
    if (count($attr) != 0) {
        foreach ($attr as $val) {
            $tmp .= " (";
            foreach ($cols as $col) {
                $tmp .= ($col === end($cols))? $col." LIKE "."'%".$val."%'" : $col." LIKE "."'%".$val."%' OR ";
            }
            $tmp .= ($val === end($attr))? ")" : ") AND";
        }
        return $tmp;
    }else{ return "1";} //regresa 1 para mostrar todos los datos de la tabla
}
include "dicc.php";
//variables POST
$serch = utf8_encode($_POST['search']);
$table = $_POST['table'];
$idx = isset($_GET['idx']) ? $_GET['idx'] : 1;
//--------------
$indexOffset = $idx != 0 ? ($idx - 1) * 10 : 0;
$attr = explode(' ', $serch); //agregamos cada palabra del search a una entrada de attr
$serverName = SVR; 
$connectionInfo = array( "Database"=>DBO, "UID"=>USR, "PWD"=>PSS, "CharacterSet" => "UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
    //-------------------------------
$where = creaWhere($attr, $COLUMNS[$DBOS[$table]]); //le metemos los atributos de busqueda y las columnas en las que debe de buscar a la funcion
$queryCount = "SELECT COUNT(*) FROM ".$DBOS[$table]." where $where" ;
$start = microtime(true);
$count = sqlsrv_fetch_array(sqlsrv_query($conn, $queryCount))[0];
file_put_contents($logFile, $queryCount."\n TOTAL de resultados: ".$count);    
if ($count == 0) { //checa si hay resultados
    $hay = 0;
}else {
    //crea la query que devolvera las columnas indicadas en el diccionario en el array SELECTS, se crea despues de confirmar que hay resultados con la primera query
    $fetch = ($count - $indexOffset) > 10 ? "FETCH NEXT 10 ROWS ONLY" : "";
    $query = "SELECT ". 
             implode(", ", $SELECTS[$DBOS[$table]]) . 
             " FROM ".$DBOS[$table]." WHERE ". $where . 
             " ORDER BY ". $COLUMNS[$DBOS[$table]][0] ." ASC".
             ($count <= 10 ? "" : " OFFSET $indexOffset ROWS $fetch");
    file_put_contents($logFile, "\n".$query, FILE_APPEND);
    $results = sqlsrv_query($conn, $query); //ejecuta la query
    $hay = 1;
    // si hay resultados extrae los headers de las columnas para despues ponerlo en la tabla html
    $end = microtime(true) - $start;
    file_put_contents($logFile, "\n tiempo de ejecución TOTAL: ".$end, FILE_APPEND);
    file_put_contents("time-data.txt", count($attr)." ".$end."\n", FILE_APPEND);
}

And this is where it marks the error exactly on the line of the while

//imprime resultados codificados a utf8 en caso de no haber resultados no hace nada
                if($hay){
                    $i = 0;
                    while($result = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC)) {
                        if ($i == 0) {
                            $headers = array_keys($result);
                            echo "<thead><tr>";
                                foreach ($headers as $head) {
                                    echo "<th> $head </th>";
                                }
                            echo "</tr></thead><tbody>";
                        }
                        $i+=1;
                        echo "<tr>";
                            foreach ($result as $col) {
                                if($col instanceof DateTime){
                                    $txt = $col->format('Y-m-d');
                                }
                                else{
                                    $txt=(string)$col; 
                                }
                                echo "<td>". utf8_encode($txt) ."</td>";
                                //echo $col;
                                //echo $col->format("Y-m-d");
                            }
                        echo "</tr>";
                    }
                }

That's it, if more code is needed I can put it

    
asked by Augustoock 13.09.2016 в 22:12
source

2 answers

2

Reading the documentation of sqlsrv_fetch_array .

Signature

array sqlsrv_fetch_array ( resource $stmt [, int $fetchType [, int $row [, int $offset ]]] )

Parameter resource $ stmt

  

stmt

     

A statement resource returned by sqlsrv_query or sqlsrv_prepare.

Looking at your code $results is obtained as a result of a call to sqlsrv_query .

Looking at the documentation for sqlsrv_query .

Signature

mixed sqlsrv_query ( resource $conn , string $sql [, array $params [, array $options ]] )

Returns something type mixed , meaning that it can return different types.

Following can be read:

  

Return values

     

Returns to statement resource on success and FALSE if an error occurred.

That is to say, if there was an error, it returns FALSE , that is, a Boolean type. As the warning indicates.

On that side, mystery solved.

Seeing the example of the documentation, the first thing it does is verify the type returned.

$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}

So my suggestion would be to modify your code accordingly to take this into account. For example:

$results = sqlsrv_query($conn, $query); //ejecuta la query
if( $results === false ) {
    $hay= 0;
    if( ($errors = sqlsrv_errors() ) != null) {
        foreach( $errors as $error ) {
            echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
            echo "code: ".$error[ 'code']."<br />";
            echo "message: ".$error[ 'message']."<br />";
    }
    //Codigo necesario para terminar la ejecución con gracia
}
    
answered by 14.09.2016 / 01:13
source
0

I think the error occurs when there are no results for the search or you have an error in the query .. try looking at how many results the query brings you.

when executing the query do something like;

$results = sqlsrv_query($conn, $query); //ejecuta la query
$row_count = sqlsrv_num_rows( $results );
if($row_count>0){
  $hay = true;
}else{
  die("No hay resultados a mostrar");
}

Greetings I hope you will be of help.

EDITO

It occurs to me that you use something like this:

if($hay){
   $i = 0;
    if($results)
        while($result = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC)) {


        if ($i == 0) {
                        $headers = array_keys($result);
                        echo "<thead><tr>";
                            foreach ($headers as $head) {
                                echo "<th> $head </th>";
                            }
                        echo "</tr></thead><tbody>";
                    }
                    $i+=1;
                    echo "<tr>";
                        foreach ($result as $col) {
                            if($col instanceof DateTime){
                                $txt = $col->format('Y-m-d');
                            }
                            else{
                                $txt=(string)$col; 
                            }
                            echo "<td>". utf8_encode($txt) ."</td>";
                            //echo $col;
                            //echo $col->format("Y-m-d");
                        }
                    echo "</tr>";
    }
    else{
        if(($errors = sqlsrv_errors()) != null) {
            foreach( $errors as $error ) {
                echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
                echo "code: ".$error[ 'code']."<br />";
                echo "message: ".$error[ 'message']."<br />";
            }
        }
    }
 }
    
answered by 13.09.2016 в 22:23