MySQL 查询没有返回结果
No results returned by MySQL query
我正在测试连接到数据库并检索结果的应用程序。它使用 PHP 和 Joomla 框架。
问题是,如果我将查询设为
$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);
}
除了 table 包含大量数据(200 多行)之外,上面的代码给出了消息 "no data returned by db"。
如果我将无效的 table 名称设为 #__coupon_member_details123
,则会产生错误 "Table does not exist"。
我不明白哪里出了问题?
在 Joomla 中,您必须使用正确的 Joomla API,就像这样。 mysql_num_rows
在 Joomla 中等价于 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);
}
我会这样做:
$query = "SELECT * FROM #__coupon_member_details";
$this->_db->setQuery($query);
$arrResult = $this->_db->loadAssocList();
$intCountResults = count($arrResult);
上面的查询会return$arrResult
中的数据,$intCountResults
中的结果数。
如果你只想要数字,那么我建议你把上面的改成:
$query = "SELECT COUNT(*) AS `totalcount` FROM #__coupon_member_details";
$this->_db->setQuery($query);
$intCountResults = $this->_db->loadResult();
这个更好,而且可以扩展。更好的是你可以做类似 SELECT count(id)
而不是 SELECT COUNT(*)
的事情(如果你有一个 id
字段)。
我正在测试连接到数据库并检索结果的应用程序。它使用 PHP 和 Joomla 框架。 问题是,如果我将查询设为
$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);
}
除了 table 包含大量数据(200 多行)之外,上面的代码给出了消息 "no data returned by db"。
如果我将无效的 table 名称设为 #__coupon_member_details123
,则会产生错误 "Table does not exist"。
我不明白哪里出了问题?
在 Joomla 中,您必须使用正确的 Joomla API,就像这样。 mysql_num_rows
在 Joomla 中等价于 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);
}
我会这样做:
$query = "SELECT * FROM #__coupon_member_details";
$this->_db->setQuery($query);
$arrResult = $this->_db->loadAssocList();
$intCountResults = count($arrResult);
上面的查询会return$arrResult
中的数据,$intCountResults
中的结果数。
如果你只想要数字,那么我建议你把上面的改成:
$query = "SELECT COUNT(*) AS `totalcount` FROM #__coupon_member_details";
$this->_db->setQuery($query);
$intCountResults = $this->_db->loadResult();
这个更好,而且可以扩展。更好的是你可以做类似 SELECT count(id)
而不是 SELECT COUNT(*)
的事情(如果你有一个 id
字段)。