警告:sqlsrv_num_rows()期望参数1为资源,布尔值为

时间:2016-09-29 23:22:39

标签: php sql excel sqlsrv

我对编程有点新,我在PHP中使用SQLSRV查询但是当导出到Excel时没有给我结果时,我抛出错误

  

警告:sqlsrv_num_rows()将参数1视为资源,布尔值在

中给出

这是代码,SQL查询本身在SQL Server中执行,但这里的Excel给了我那个错误,而网络搜索和搜索却找不到答案,这就是代码:

<?php

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="Movimientos Cancelados del Mes.xls"');
header('Cache-Control: max-age=0');

$server = "server";
$info = array("Database"=>"DB","UID"=>"USR","PWD"=>"" );
$conn = sqlsrv_connect($server, $info);
$param = array('ReturnDatesAsStrings'=> true);
$opt = array("Scrollable" => SQLSRV_CURSOR_KEYSET);

$per = $_GET["periodo"];
$eje = $_GET["ejercicio"];
$mov = 'Movimiento';
$est = 'Estatus';
$cli = 'Cliente';
$rfc = 'RFC';
$tot = 'Total';
$fec = 'Fecha Timbrado';
$uuid = 'UUID';
$cert = 'Certificado SAT';
$sql = "select v.MovID as '$mov',v.Estatus as '$est',v.Cliente as '$cli',cte.rfc as '$rfc',(v.Importe+v.Impuestos)as '$tot', c.FechaTmibrado as '$fec', c.UUID as '$uuid',c.noCertificadoSAT as '$cert'
from Venta V join CFD c on v.MovID = c.MovID join cte on v.cliente = cte.cliente 
where V.Estatus = 'Cancelado' and c.Periodo = '$per' and c.Ejercicio = '$eje' and  c.Empresa = 'MGJ' 
order by FechaEmision";

$query = sqlsrv_query($conn, $sql);

$campos = sqlsrv_num_rows($query);

$i = 0;

echo "<table border=''><tr>";
echo "<th>$mov</th>";
echo "<th>$est</th>";
echo "<th>$cli</th>";
echo "<th>$rfc</th>";
echo "<th>$tot</th>";
echo "<th>$uuid</th>";
echo "<th>$cert</th>";

while ($i<$campos) {
    echo "<td>".sqlsrv_get_field($query,$i);
    echo "</td>";
    $i++;
}
    echo "</tr>";
while($row=sqlsrv_fetch_array($query)){
    echo "<tr>";
    for ($j=0; $j < $campos; $j++) { 
        echo "<td>".$row[$j]."</td>";
    }
    echo "</tr>";
}
echo "</table>";
   sqlsrv_close( $conn);
print_r(sqlsrv_errors(),true);
?>

1 个答案:

答案 0 :(得分:0)

  

警告:sqlsrv_num_rows()将参数1视为资源,布尔值在

中给出

这意味着,您的查询不会返回资源对象,因为查询无法编译或运行。

要了解发生这种情况的原因,您可以使用sqlsrv_errors()

if( ($errors = sqlsrv_errors() ) != null) {
    foreach( $errors as $error ) {
        echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
        echo "code: ".$error[ 'code']."<br />";
        echo "message: ".$error[ 'message']."<br />";
    }
}