2016-09-29 120 views
0

給出我有點新的編程,我有一個SQLSRV的PHP查詢,但當輸出到Excel不給我的結果,我拋出錯誤警告:sqlsrv_num_rows()期望參數1是資源,布爾在

警告: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); 
?> 
+0

你'$ query'失敗,運行檢查錯誤。我也不清楚'excel'與此有什麼關係,Excel是否有一個可以執行PHP的驅動程序?你也開放SQL注入。 – chris85

+0

它也給你一個關於該錯誤的行號。你想給我們一些關於你的代碼哪行錯誤的線索,我們只是看看它,直到我們手動編譯它在我們的頭上 – RiggsFolly

+0

閱讀http://php.net/manual/en /function.sqlsrv-query.php你會發現當你運行你的查詢時,它失敗了,這意味着$ query是FALSE;當您嘗試傳遞布爾而不是資源時,這反過來會導致錯誤。 我可以建議你考慮使用PDO嗎? – Rawrskyes

回答

0

警告:sqlsrv_num_rows()預計參數1是資源,在

這意味着給定的boolean,查詢不返回的資源對象,因爲查詢無法編譯或運行。

要知道爲什麼發生這種情況,你可以使用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 />"; 
    } 
} 
+0

爲什麼會那我可以問一下,代表OP – RiggsFolly

+0

@RiggsFolly我試圖找出它 –

+0

_你的查詢沒有返回資源object_,因爲查詢無法編譯或運行,會做 – RiggsFolly

相關問題