[英]No results returned by MySQL query
I am testing an application which connects to database and retrieve results. 我正在测试连接到数据库并检索结果的应用程序。 It uses PHP, and Joomla framework.
它使用PHP和Joomla框架。 The thing is that if I put a query as
问题是,如果我将查询
$query = "SELECT * FROM #__coupon_member_details";
$this->_db->setQuery($query);
$result = $this->_db->query();
$number = mysql_num_rows($result);
if($number == 0 ){
JFactory::getApplication()->enqueueMessage("no data returned by db");
}else{
JFactory::getApplication()->enqueueMessage($number);
}
The above code gives message "no data returned by db" except the fact that the table contains a lot of data (200+ rows). 上面的代码给出消息“ db没有返回数据”,除了表包含大量数据(200多个行)的事实。
If I put invalid table name as #__coupon_member_details123
, then it produces an error saying "Table does not exist". 如果我将无效的表名设置为
#__coupon_member_details123
,则会产生错误,提示“表不存在”。
I fail to understand what is wrong ? 我不明白怎么了?
In Joomla you have to use correct Joomla API which goes like this. 在Joomla中,您必须使用正确的Joomla API。
mysql_num_rows
equivalent in Joomla is getNumRows
在Joomla中等效的
mysql_num_rows
是getNumRows
$query = $this->_db->getQuery(true);
$query = "SELECT * FROM #__coupon_member_details";
$this->_db->setQuery($query);
$result = $this->_db->query();
$numRows = $this->_db->getNumRows();
if($numRows == 0 ){
JFactory::getApplication()->enqueueMessage("no data returned by db");
}else{
JFactory::getApplication()->enqueueMessage($number);
}
I would do it this way: 我会这样:
$query = "SELECT * FROM #__coupon_member_details";
$this->_db->setQuery($query);
$arrResult = $this->_db->loadAssocList();
$intCountResults = count($arrResult);
The above query will return the data in $arrResult
, and the number of results in $intCountResults
. 上面的查询将在
$arrResult
返回数据,并在$intCountResults
中返回结果数。
If you only want the number, then I suggest you change the above to: 如果您只想要数字,那么我建议您将以上内容更改为:
$query = "SELECT COUNT(*) AS `totalcount` FROM #__coupon_member_details";
$this->_db->setQuery($query);
$intCountResults = $this->_db->loadResult();
This is better and is scalable. 这样更好,并且可以扩展。 Even better you could do something like SELECT
count(id)
instead of SELECT COUNT(*)
(if you have an id
field). 更好的是,您可以执行类似SELECT
count(id)
而不是SELECT COUNT(*)
(如果您有id
字段)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.