我正在运行SQL查询并使用PHP获取结果计数。下面是我的语法的相关部分,我想要做的是,如果返回的计数是> = 1然后显示网格(因为它将填充1或更多行),但如果返回的行数是0然后在屏幕上显示警告,通知用户。
我对代码的问题是它总是返回网格!
<?php
//Connection to server to run sql query and return results
$numofrows = mssql_num_rows($tsql);
?>
if ($numofrows >= 1) {
//Build out HTML Table
} else {
//write on screen there are no results to display
}
修改
这就是我设置它的方式,它与评论中的链接相同
<?php
//Connection to server to run sql query and return results
$numofrows = mssql_num_rows($tsql);
?>
if ($numofrows >= 1) {
<table border="1">
<thead>
<tr>
<th >Header 1 </th>
<th>Header 2 </th>
<th>Header 3 </th>
<th>Header 4 </th>
<th>Header 5</th>
<th>Header 6 </th>
</tr>
</thead>
<tbody>
<?php
foreach( $query as $res ) {
print "<tr>";
print "<td>" .$res->Field1."</td>";
print "<td>" .$res->Field2."</td>";
print "<td>" .$res->Field3."</td>";
print "<td>" .$res->Field4."</td>";
print "<td>" .$res->Field5."</td>";
print "<td>" .$res->Field6."</td>";
print "</tr>";
}
?>
} else {
echo "<strong>No Results</strong>"
}
答案 0 :(得分:1)
这是一个近似的例子,可以帮助你。
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Select Database
mysqli_select_db($conn, "test");
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body bgcolor="#06160F">
<table frame="hsides" style="color:#ffffff;">
<!-- Headers of the table -->
<tr>
<th>Header 1 </th>
<th>Header 2 </th>
<th>Header 3 </th>
<th>Header 4 </th>
<th>Header 5</th>
<th>Header 6 </th>
</tr>
</table>
</div>
<div>
<div>
<table border="1" width="960px">
<?php
$sql = "SELECT * FROM abc";
$result = mysqli_query($conn,$sql);
if($result)
{
if ($result->num_rows > 0)
{echo"<table>";
// output data of each row
while($row = $result->fetch_assoc())
{
echo"<tr>";
echo"<td width=120px align=\"center\">".$row["feild1"]."</td>";
echo"<td width=170px align=\"center\">".$row["feild2"]."</td>";
echo"<td width=120px align=\"center\">".$row[""feild3"]."</td>";
echo"<td width=170px align=\"center\">".$row["feild4"]."</td>";
echo"<td width=420px align=\"center\">".$row["feild5"]."</td>";
echo"<td width=420px align=\"center\">".$row["feild6"]."</td>";
echo"</tr>";
}
echo"</table>";
}
else
echo "<h3 align=\"center\">Nothing to show.</h3>";
}
else
echo "<br> Database error.";
$conn->close();
?>
</table>
</div>
<br>
</div>
</body>
</html>
顺便说一句,我正在使用MySQL。
答案 1 :(得分:0)
您还可以查看以下答案:Checking for empty result (php, pdo, mysql)
我想也是,你应该使用PDO。
答案 2 :(得分:0)
你的if循环在php部分之外,所以它不会被评估