如果没有结果,则将PHP SQL查询清除为值0

时间:2011-02-22 23:51:29

标签: php mysql conditional-statements

我编写了一些PHP代码,如果返回结果将返回一个值,如果没有返回结果则返回0。但是,该功能非常麻烦且难以解析。我想知道是否有更简洁的方法来重写我的代码。提前谢谢!

$last_question_sql="SELECT DISTINCT QUESTION_ID
                FROM branching_survey_responses
                WHERE QUESTION_ID=(SELECT Max(QUESTION_ID)
                           branching_survey_responses
                           WHERE CUSTOMER_ID=232
                        AND SET_ID=2)
                AND CUSTOMER_ID=232
                AND SET_ID=3";

        $last_question_result=mysql_query($last_question_sql);

        if($last_question_status=mysql_fetch_assoc($last_question_result)){
            $last_question=$last_question_status['QUESTION_ID'];
        }
        else{
            $last_question= 0;
        }

1 个答案:

答案 0 :(得分:0)

编辑:

我不确定,但如果您使用此代码获取最后插入的项目,则可以使用mysql_insert_id()示例:

成功执行INSERT查询后,您可以检索最后一个ID,如

$last_question = mysql_insert_id();

function last_question($cid, $sid1, $sid2)
{
  $question = 0;
  $result = mysql_query(
  "SELECT DISTINCT QUESTION_ID 
   FROM branching_survey_responses 
   WHERE QUESTION_ID=(SELECT Max(QUESTION_ID) branching_survey_responses
   WHERE CUSTOMER_ID={$cid}
   AND SET_ID={$sid1})
   AND CUSTOMER_ID={$cid}
   AND SET_ID={$sid2}");
  if ($status = mysql_fetch_assoc($result)) {
    $question = $status['QUESTION_ID'];
  }
  return $question;
}