Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Natalia Bruscato

[Resolvido] Busca com campos não obrigatorios

Recommended Posts

Olá!Boa tarde!

 

Estou trabalhando com um fomrulário de Busca com campos não obrigatorios

 

e gostaria de montar a string dinamicamente, por exemplo:

Se o campo data estiver vazio ele não entra na string caso contrario entra...

 

Alguem me dá uma idéia?

 

Obrigada!

Compartilhar este post


Link para o post
Compartilhar em outros sites

olha este exemplo, onde você pode fazer uma busca usando o E (and) OU (or), ou a palavra EXATA

tudo isso montando dinamicamente sua string SQL, você pode até pegar a tabela que quiser também

'------------- SEARCH
'******************************************************
'******************************************************

On Error Resume Next



PAGE_SIZE = 20  ' display number of results


strURL = Request.ServerVariables("URL") ' the URL or Query string



'------------- q = the input text


strSearch = Request.QueryString("q") ' the input text

If strSearch = "" Then

Server.htmlencode(Trim(Request.Form("q")))

End If


strSearch = Replace(strSearch, "'", "''")


'----------- p = RESULT PAGING

IF isnumeric(Request.QueryString("p")) = True OR Request.QueryString("p") = "" THEN

			  ' Retrieve page to show or default to the first
			  If Request.QueryString("p") = ""  OR Request.QueryString("p") < 1 Then
			  	iPageCurrent = 1
			  Else
			  	iPageCurrent = CInt(Request.QueryString("p"))
		  	  End If

ELSE

iPageCurrent = 1


END IF

p = iPageCurrent



'----------------- t = SELECTED TABLE

IF isnumeric(Request.QueryString("t")) = True OR Request.QueryString("t") = "" THEN

			  ' Retrieve t

			  If Request.QueryString("t") = ""  OR Request.QueryString("t") < 1 Then
			  	searchTable = 1 '1
			  Else

			  	searchTable =  1 'CInt(Request.QueryString("t"))

		  	  End If

ELSE

searchTable = 2 '1

END IF


'------------------- m = SEARCH METHOD

IF isnumeric(Request.QueryString("m")) = True OR Request.QueryString("m") = "" THEN

			  ' Retrieve m
			  If Request.QueryString("m") = ""  OR Request.QueryString("m") < 1 Then
			  	strMethod = 2
			  Else
			  	strMethod = CInt(Request.QueryString("m"))
		  	  End If

ELSE

strMethod = 2


END IF



'---------------THE FORM
%>

                 <form method="get" action="<%= strURL %>">
				<p>
				<input type="radio" name="m" value="1" <% IF strMethod = 1 THEN response.write "checked=""checked""" END IF%> />
                   	E
                   	<input type="radio" name="m" value="2" <% IF strMethod = 2 OR strMethod = "" THEN response.write "checked=""checked""" END IF%> />
                   	OU
                   	<input type="radio" name="m" value="3" <% IF strMethod = 3 THEN response.write "checked=""checked""" END IF%> />
                  	Exato</p>

				<p><input type="text" class="input3" name="q" value="<%= Trim(strSearch) %>" /></p>

                   <p><input type="submit" value="Procura" />
                   <br /><br /></p>

                 </form>
                 <%



If strSearch <> "" Then


	Session("strSearch") = strSearch

	IF isnumeric(Request.QueryString("t")) = True OR Request.QueryString("t") = "" THEN

					  ' Retrieve t

					  If Request.QueryString("t") = ""  OR Request.QueryString("t") < 1 Then
						searchTable = 1 '1
					  Else

						searchTable = 1 'CInt(Request.QueryString("t"))

					  End If

	ELSE

	searchTable = 1' 1

	END IF




	' THE TABLES

	Select Case searchTable

		Case CInt("1")

				dbTable = "tMessages"
				'strDBPath = Server.MapPath("/blogg/blog.mdb")


		Case CInt("2")

				'dbTable = "events"
				'strDBPath = Server.MapPath("")

		Case Else

				dbTable = "tMessages"
				'strDBPath = Server.MapPath("")


	End Select



'------------------ SQL



			  'SPLIT STRING INTO ARRAYS
			  'FOR and AND or CLAUSE SQL


'----------------- SQL tMessages blog table

IF searchTable = "1" THEN
IF strMethod < 3 THEN


		If strMethod = 1 Then
		strSplit = Replace(strSearch," "," and ")
		Else
		strSplit = Replace(strSearch," "," or ")
		End If


		colTerms = split(strSplit," and ",-1,1)

		iUpperTerms = UBound(colTerms)

		strWhereClause = ""



		'FIELD CLAUSES

		nr = 0
		Do while nr <= 5

		nr = nr + 1

		searchField = CInt(nr)

		Select Case searchField

			Case CInt("1")

				strTableInClause = "fDate"

			Case CInt("2")

				strTableInClause = "fHeadline"

			Case CInt("3")

				strTableInClause = "fMessage"

			Case CInt("4")

				strTableInClause = "fAuthor"

			Case CInt("5")

				strTableInClause = "fnota"

			'Case Else


		End Select


			  For iLoop = LBound(colTerms) to iUpperTerms
				orTerms = split(colTerms(iLoop)," or ",-1,1)
				iUpperOrTerms = UBound(orTerms)
				strWhereClause = strWhereClause & ""

					for iOrLoop = LBound(orTerms) to iUpperOrTerms
							strWhereClause = strWhereClause & strTableInClause & " LIKE '%" & Trim(orTerms(iOrLoop)) & "%' "

						if iOrLoop < iUpperOrTerms then
							strWhereClause = strWhereClause & " OR "
						end if
					next

					strWhereClause = strWhereClause & ""

					if iLoop < iUpperTerms then
							strWhereClause = strWhereClause & " AND "
					end If

			  Next

			  if nr <= 4 then
			  strWhereClause = strWhereClause & " OR "
			  end if

	Loop


ELSE

' METHOD 3 EXACT PHASE WHERE

strWhereClause = "fDate LIKE '%" & strSearch & "%' OR fHeadline LIKE '%" & strSearch & "%' OR fMessage LIKE '%" & strSearch & "%' OR fAuthor LIKE '%" & strSearch & "%'  OR fnota LIKE '%" & strSearch & "%'"

END IF


strWhereClause2 = "WHERE (" & strWhereClause & ") AND (online = CBool(-1))"

' ORDER BY
strOrderClause = "ORDER BY fdate DESC"



IF strMethod = 3 THEN

	strSQL = "SELECT * FROM "& dbTable &" "& strWhereClause2 &" "& strOrderClause &";"

ELSE

	strSQL = "SELECT * FROM "& dbTable &" "& strWhereClause2 &" "& strOrderClause &";"

END IF


END IF

Response.write strSQL

'---------- END SQL tMessages BLog




'--------- CONNECTION OPEN & EXE SQL


Set myRecSet = Server.CreateObject("ADODB.Recordset")
myRecSet.PageSize  = PAGE_SIZE
myRecSet.CacheSize = PAGE_SIZE

' constants
adOpenStatic = 3
adLockReadOnly = 1
adCmdText = &H0001


myRecSet.Open strSQL, sConn, adOpenStatic, adLockReadOnly, adCmdText


iRecordCount = myRecSet.RecordCount
iPageCount   = myRecSet.PageCount



		   ' THE RESULT COUNTER

			strCountRecord = iRecordCount

			If iPageCurrent = 1 Then

			  		strCount = strCountRecord - iRecordCount + 1

			Else

					strCount = iPageCurrent * PAGE_SIZE - PAGE_SIZE + 1

					'strCountRecord -  + * iPageCurrent

			End If



If iRecordCount = 0 Then


	%>			<p>Desculpa, sua busca não retornou resultados.<br />
                   Sua Busca por - <b><%=strSearch%></b> - não retornou documentos.</p>

                 <%
Else

	myRecSet.AbsolutePage = iPageCurrent

	If iRecordCount <= PAGE_SIZE then
	toRecord = iRecordCount
	else
	toRecord = strCount + PAGE_SIZE - 1
	End if
	If toRecord => iRecordCount then
			toRecord=  iRecordCount
	End if

	%>

                       <p>Mostrando  resultado <%=strCount%> - <%=toRecord%> de <%=iRecordCount %>. Paginas <%= iPageCurrent %> / <%= iPageCount %>. </p>
					<br /><p>
                       <%

	If iPageCurrent > 1 Then
		%>
                       <a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(strSearch) %>&p=<%= iPageCurrent - 1 %>" title="Previous">
                       ‹‹</a>
                       <%
	End If


	For I = 1 To iPageCount
		If I = iPageCurrent Then

		%>

                       <%= I %>
                       <%
		Else
			%>
                       <a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(strSearch) %>&p=<%= I %>" title="<%= I %>"><%= I %></a>
                       <%
		End If
	Next 'I

	If iPageCurrent < iPageCount Then
		%>
                       <a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(strSearch) %>&p=<%= iPageCurrent + 1 %>" title="Next"> ››</a>
                       <%
	End If
	%></p>

       <%

'----------------THE RESULT LOOP


	Do While Not myRecSet.EOF And myRecSet.AbsolutePage = iPageCurrent


				intNumMatches = 0
				allregText = ""
				regWriteOut = ""

				If strSearch = " " then
					strSearch = ""
				End if

				Set objRegExp = New RegExp
				objRegExp.Global = True
				objRegExp.IgnoreCase = True


				If dbTable = "tMessages" then
				allregText = myRecSet.Fields("fDate").Value & " " & myRecSet.Fields("fHeadline").Value & " " & myRecSet.Fields("fMessage").Value & " " & myRecSet.Fields("fAuthor").Value
				End If


				allregText = Replace(allregText, "<", "", 1, -1, 1)
				allregText = Replace(allregText, ">", "", 1, -1, 1)
				allregText = UTFtoISO(allregText)

				If strMethod = 3 then

				'Set the pattern to search for
				objRegExp.Pattern = strSearch

				'Search the file for the phrase
		 		Set objMatches = objRegExp.Execute(allregText)

				'Get the number of times the phrase is matched
				intNumMatches = objMatches.Count

				End if

				If strMethod < 3 then

				sarySearchWord = Split(strSearch, " ")
				For intSearchLoopCounter = 0 to UBound(sarySearchWord)

				'Set the pattern to search for
				objRegExp.Pattern = "" & sarySearchWord(intSearchLoopCounter) & ""

				'Search the file for the phrase
				Set objMatches = objRegExp.Execute(allregText)

				intNumMatches = intNumMatches + objMatches.Count

				Next
				End if



		 		If intNumMatches => 1 Then

				If intNumMatches > 1 then
				regWriteOut = "" & intNumMatches & " hits."
				Else
				regWriteOut = "" & intNumMatches & " hit."
				End If

		 		End If

				Set objRegExp = Nothing



		%>


				<% IF dbTable = "tMessages" THEN %>
				<p><br /><br />
				<%=strCount%>. <a href="default.asp?id=<%= myRecSet.Fields("id").Value %>" title="<%=myRecSet.Fields("fHeadline").Value%>"><%= myRecSet.Fields("fHeadline").Value %></a>
				<br /><%= RemoveHTML(Left(myRecSet.Fields("fMessage").Value,instrrev(Left(myRecSet.Fields("fMessage").Value,280),"")))%>
				<br />
				Postado: <%= year(myRecSet.Fields("fdate").Value)  & "-" & right("00" & cstr(month(myRecSet.Fields("fdate").Value)),2) & "-" & right("00" & cstr(day(myRecSet.Fields("fdate").Value)),2) & ". " & regWriteOut%>
				</p>
				<% END IF%>


          <%


					strCount = strCount + 1
		myRecSet.MoveNext
	Loop


'----------------THE RESULT LOOP END
	%>
                   	<br /><br /><p>
                       <%

	If iPageCurrent > 1 Then
		%>
                       <a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(Session("strSearch")) %>&p=<%= iPageCurrent - 1 %>" title="Previous">‹‹</a>
                       <%
	End If


	For I = 1 To iPageCount
		If I = iPageCurrent Then
			%>

                       <%= I %>
                       <%
		Else
			%>
                       <a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(Session("strSearch")) %>&p=<%= I %>" title="<%= I %>"><%= I %></a>
                       <%
		End If
	Next 'I

	If iPageCurrent < iPageCount Then
		%>
                       <a href="<%= strURL %>?m=<%= Server.URLEncode(strMethod) %>&t=<%= Server.URLEncode(searchTable) %>&q=<%= Server.URLEncode(Session("strSearch")) %>&p=<%= iPageCurrent + 1 %>" title="Next">››</a>
                       <%
	End If
	%>

                   <%

	End If

%></p>
<%

	' CLOSE & DISPOSE

	myRecSet.Close
	Set myRecSet = Nothing
	End If



'---------------- SEARCH END


'******************************************************
'******************************************************
%>

Compartilhar este post


Link para o post
Compartilhar em outros sites

basta fazer um IF testando a condição

Compartilhar este post


Link para o post
Compartilhar em outros sites

basta fazer um IF testando a condição

 

Olá,Amigos obrigada pela atenção!

Consegui fazer utilizando IF como Mário Monteiro sugeriu.

 

Ficou assim...

 

strSQL = "Set dateformat dmy; SELECT * FROM noticia WHERE id_noticia > 0 " 

If titulo <> "" Then 
       strSQL = strSQL & " AND titulo LIKE '%"&titulo&"%'" 
End If 

If categ <> "" Then 
       strSQL = strSQL & " AND categoria = '"&categ&"'" 
End If 

If fonte <> "" Then 
       strSQL = strSQL & " AND fonte = '"&fonte&"'" 
End If 

If data <> "" Then 
       strSQL = strSQL & " AND data = '"&data&"'" 
End If 


Set ObjRs = objConn.Execute(strSQL)

 

Muito Obrigada! :P

Compartilhar este post


Link para o post
Compartilhar em outros sites

Parabéns pela solução

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.