需要帮助,我尝试在Sql中使用Select if语句
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
When z.z_status='1' and z.z_id = '".$vid."'
else JError::raiseError(404, "Message");
";
目标目标是:z_status=1
时显示列表,J Error
时显示z_status=0
。然而,它不起作用。这个功能很好用
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = '".$vid."'
";
但是,当尝试使用else语句进行修改时,它不起作用。
编辑 - 完整功能代码: -
$database =& JFactory::getDBO();
global $Itemid;
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = '".$vid."'
";
$database->setQuery($sql);
$rows = $database->loadObjectList();
return $rows[0];
答案 0 :(得分:0)
您混淆了SQL和PHP以及Joomla:您编写的第二个查询是您要运行的查询。但逻辑需要在php中处理。你的sql引擎不知道“else”(这是php)或JError(这是Joomla)。不要说错误使用“ - 因为你写的只是语法错误。
$db = JFactory::getDbo();
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = " . $db->quote($vid);
$db->setQuery($sql);
if ($result = $db->loadObject()) {
// the query returned something, you can use the result object
echo $result->prod_name;
} else {
if ($db->getErrorNum()) {
JError::raiseError(500, "Something went horribly wrong, the query returned the error ". $db->getErrorMsg());
} else {
echo "Your query returned no records i.e. no records satisfy the z_status=1 condition";
}
}
最后,404“未找到”,但它指的是请求,而不是应用程序中的数据。如果查询错误输出,您可能希望返回500,而对于所有其他请求,您可能希望返回200。有关状态代码的详情,请参阅此处:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html