Тема: Помогите правильно сформулировать запрос
Попытаюсь выложить тут как можно больше инфо и объяснить что мне нужно... Не судите строго, я новичек в этом деле
При регистрации на моем вебсайте пользователь заполняет форму где он вводит имя, пароль, дату рождения и т.п. Вконце этой формы он выбирает одну или несколько специализаций. Сразу оговорюсь, если пользователь выбирает только одну специализацию, то все работает ок. Если же больше одной, то возникает пробема.
Вот как выглядит запрос при регистрации:
// Add member details to DB table
function addMember()
{
global $dbObj;
$userProfileId = generateRandNumber(3);
$activationCode = generateCode(40);
$DOB = trim($_POST['date'])."/".trim($_POST['month'])."/".trim($_POST['year']);
$nowYear = date('Y',time());
$age = $nowYear - trim($_POST['year']);
if (count($_POST['special']) > 0) {
$special = implode(",", $_POST['special']);
}
$sqlInsert = "INSERT INTO
".USERS."
SET
emailId = '".trim($_POST['emailId'])."',
userName = '".$this->username."',
password = '".base64_encode($this->password)."',
registerDate = NOW(),
usertype = 'user',
profileType = '".trim($_POST['profileType'])."',
activationCode = '".$activationCode."',
userProfileId = '".$userProfileId."',
gender = '".trim($_POST['gender'])."',
dob = '".$DOB."',
age = '".$age."',
accountType = 'free',
status = 'Inactive',
specialise = '".$special."' ";
$res = $dbObj->query($sqlInsert);
$this->mysqlInsertId = mysql_insert_id();
$this->sendActivationCode($activationCode);
if ($res) {
return $this->mysqlInsertId;
} else {
return false;
}
}// end of fun
В бд специализации разделены запятой.
Далее есть форма поиска пользователей. В ней вводятся параметры типа возраст, пол и т.п. Вконце поиска есть опция искать по специализации. Можно выбрать только одну специализацию чтобы осуществить поиск. Но в случае если пользоваетль указал при регистрации несколько специализаций он не отображается в результате поиска...
Вот запрос посылаемый при поиске....
/**
* This fun is call from result page
* This fun is use for searching profiles
* return 2D array
*/
function ***Search($limit = 0, $page = 0,$forWhat = '')
{
global $dbObj;
$search = "";
$detail = array();
$add = '';
if ($limit != 0) {
$offset = ($page * $limit) - $limit;
$add = " LIMIT $offset, $limit";
}
if($_SESSION['sSearch']['profileType'] != ""){
$search = " profileType = '".trim($_SESSION['sSearch']['profileType'])."' ";
}
if($_SESSION['sSearch']['country'] != ""){
$search .= " AND country = '".trim($_SESSION['sSearch']['country'])."' ";
}
if($_SESSION['sSearch']['state'] != ""){
$search .= " AND state = '".trim($_SESSION['sSearch']['state'])."' ";
}
if($_SESSION['sSearch']['specialise'] != ""){
// Эту строку убираем $search .= " AND specialise = '".trim($_SESSION['sSearch']['specialise'])."' ";
$search .= " AND specialise LIKE '%".trim($_SESSION['sSearch']['specialise'])."%' "; // Здесь делаем выборку с помощью LIKE.
}
if($_SESSION['sSearch']['profileType'] == "Модель"){
if($_SESSION['sSearch']['ageStart'] < $_SESSION['sSearch']['ageEnd']){
$search .= " AND (age >= '".trim($_SESSION['sSearch']['ageStart'])."' AND age <= '".trim($_SESSION['sSearch']['ageEnd'])."')";
}
if($_SESSION['sSearch']['gender'] != ""){
$search .= " AND gender = '".trim($_SESSION['sSearch']['gender'])."' ";
}
if($_SESSION['sSearch']['shFeet'] < $_SESSION['sSearch']['ehFeet']){
$search .= " AND (feet >= '".trim($_SESSION['sSearch']['shFeet'])."' AND feet <= '".trim($_SESSION['sSearch']['ehFeet'])."')";
}
}
if($search != ""){
$con1 = " AND ".$search;
}
if($_SESSION['preQuery'] == ""){
$sql = "SELECT
*
FROM
".USERS."
WHERE
userType = 'user'
".$con1."
ORDER BY userId DESC";
$_SESSION['preQuery'] = $sql;
}else{
$sql = $_SESSION['preQuery'];
}
$sql = $sql.$add;
$dbObj->query($sql);
//echo $sql;
if($dbObj->nf() > 0){
if($forWhat == "returnTotal"){
return $dbObj->nf();
}else{
while($dbObj->next_record()){
$detail[] = $dbObj->Record;
}
}
}
return $detail;
}//end of fun
Вот это относится к странице результатов:
/**
* This fun is call from result page
* This fun is use for searching profiles
* return 2D array
*/
function ***Search($limit = 0, $page = 0,$forWhat = '')
{
global $dbObj;
$search = "";
$detail = array();
$add = '';
if ($limit != 0) {
$offset = ($page * $limit) - $limit;
$add = " LIMIT $offset, $limit";
}
if($_SESSION['sSearch']['profileType'] != ""){
$search = " profileType = '".trim($_SESSION['sSearch']['profileType'])."' ";
}
if($_SESSION['sSearch']['country'] != ""){
$search .= " AND country = '".trim($_SESSION['sSearch']['country'])."' ";
}
if($_SESSION['sSearch']['state'] != ""){
$search .= " AND state = '".trim($_SESSION['sSearch']['state'])."' ";
}
if($_SESSION['sSearch']['specialise'] != ""){
// Убираем $search .= " AND specialise = '".trim($_SESSION['sSearch']['specialise'])."' ";
$search .= " AND specialise LIKE '%".trim($_SESSION['sSearch']['specialise'])."%' "; // Здесь делаем выборку с помощью LIKE.
}
if($_SESSION['sSearch']['profileType'] == "Модель"){
if($_SESSION['sSearch']['ageStart'] < $_SESSION['sSearch']['ageEnd']){
$search .= " AND (age >= '".trim($_SESSION['sSearch']['ageStart'])."' AND age <= '".trim($_SESSION['sSearch']['ageEnd'])."')";
}
if($_SESSION['sSearch']['gender'] != ""){
$search .= " AND gender = '".trim($_SESSION['sSearch']['gender'])."' ";
}
if($_SESSION['sSearch']['shFeet'] < $_SESSION['sSearch']['ehFeet']){
$search .= " AND (feet >= '".trim($_SESSION['sSearch']['shFeet'])."' AND feet <= '".trim($_SESSION['sSearch']['ehFeet'])."')";
}
}
if($search != ""){
$con1 = " AND ".$search;
}
if($_SESSION['preQuery'] == ""){
$sql = "SELECT
*
FROM
".USERS."
WHERE
userType = 'user'
".$con1."
ORDER BY userId DESC";
$_SESSION['preQuery'] = $sql;
}else{
$sql = $_SESSION['preQuery'];
}
$sql = $sql.$add;
$dbObj->query($sql);
//echo $sql;
if($dbObj->nf() > 0){
if($forWhat == "returnTotal"){
return $dbObj->nf();
}else{
while($dbObj->next_record()){
$detail[] = $dbObj->Record;
}
}
}
return $detail;
}//end of fun
Пожалуйста, помогите сделать так чтобы в результатах отображались пользователи которые выбрали несколько специализаций.
Заранее благодарен
P.S Если нужна какая-то еще инфо чтобы решить мою проблему, я ее выложу