[英]Count number of rows in SQL database
I am trying to view how many rows there are based on a SQL query using PHP. 我试图根据使用PHP的SQL查询来查看有多少行。
I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query. 我似乎能够查询数据库并从一行返回字段,但似乎无法根据同一查询找出有多少行。
<?php
$host = 'localhost';
$user = 'MyUsername';
$pass = 'MyPassword';
$database = 'MyDatabase';
$con=mysqli_connect($host,$user,$pass ,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
mysqli_close($con);
?>
All it returns is the text Rows on the screen, without the number of rows at the start. 它返回的只是屏幕上的文本“ 行数”,开头没有行数。
Like I said, this same query works and returns a value if I try and select a row using: 就像我说的一样,如果我尝试使用以下命令选择一行,则该查询有效并返回值:
while($row = mysqli_fetch_array($result))
{
echo $row["test"];
}
Anyone know why it won't return the number of rows? 有人知道为什么它不返回行数吗?
You are using MySQLi. 您正在使用MySQLi。 Because of you don't have a mysql query, mysql_num_rows doesn't return desired value.
由于您没有mysql查询,因此mysql_num_rows不会返回所需的值。 You have to replace your mysql function with mysqli equal:
您必须将mysqli函数替换为mysqli equal:
$num_rows = mysqli_num_rows($result);
You are using Mysqli
to you should use mysqli_num_rows
您正在使用
Mysqli
,应使用mysqli_num_rows
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$ result = mysqli_query($ con,“ SELECT * FROM MyTable WHERE test ='123'AND test2 ='456'”); $num_rows = mysqli_num_rows($result);
$ num_rows = mysqli_num_rows($ result);
If you want only count
then you can directly use count(*)
like this:- 如果只想
count
则可以像这样直接使用count(*)
:-
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
$ result = mysqli_query($ con,“从MyTable中选择COUNT(*),其中test ='123'和test2 ='456'”));
echo $result;
回声$结果;
I'll do some thing like this: 我会做这样的事情:
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.