Query error in Mysql using PHP

Asked

Viewed 53 times

0

Could you explain to me why PHP code does not execute variable code (this code is a query) in the ELSE part.

When the IF (Ifcontains complements of a query that will be executed in mysqli) is not executed, it automatically enters Else (which also contains complements of a query that will be executed in mysqli). Only the ELSE variable is not populated or for some reason is not executed. The IF variable usually happens.

Since I put a test variable inside IF and ELSE, and when IF is not executed, and I display the ELSE variable, it is stated that the ELSE variable has been filled.

You could help me ?

//CÓDIGO PARA PREENCHIMENTO DA LISTA COM OS DADOS DA PESQUISA 
	
	$('#formulario-consulta').submit(function(e)
	{			
		e.preventDefault();
		var formulario = $(this);
		var retorno = inserirFormulario(formulario);
	
	});
  
  function inserirFormulario(dados)
	{
		$.ajax
		({
			//dataType: "json",
			type:"POST",
			data:dados.serialize(),
			url:"interface-resultado-pesquisa.php",
			async:false
			
		}).done(function(data)
		{
			
			var atividades = "";
			
			$.each($.parseJSON(data), function(chave, valor)
			{		


				

			
				atividades += '<tr id="'+ valor.codigo +'">';
				atividades += '<td>' + valor.codigo + '</td>';
				atividades += '<td>' + valor.COD + '</td>';
				atividades += '<td>' + valor.EMPRESAS + '</td>';
				atividades += '<td>' + valor.TRIBUTACAO + '</td>';
				atividades += '<td>' + valor.TIPO_ATIVIDADE + '</td>';
				atividades += '<td>' + valor.DT_VENCIMENTO + '</td>';
				atividades += '<td>' + valor.DT_INICIO + '</td>';
				atividades += '<td>' + valor.DT_FIM + '</td>';
				//atividades += '<td><button class="btn-warning" value="'+ valor.codigo +'">Detalhes</button></td>';
				
				
				if(valor.STATUS == "INICIADO")
				{
					atividades += '<td><button type="button" class="btn" style="background-color: ForestGreen; color:white; font-weight: bold" value="'+ valor.codigo +'" id="' + valor.STATUS +'">'+ valor.STATUS +'</button></td>';
				}
				
				else if(valor.STATUS == "CONCLUIDO")
				{
					atividades += '<td><button type="button" class="btn" style="background-color: DodgerBlue; color:white; font-weight: bold" value="'+ valor.codigo +'" id="' + valor.STATUS +'">'+ valor.STATUS +'</button></td>';
				}
							
				else if(valor.STATUS == "CONCLUIDO_VENCIDO")
				{
					atividades += '<td><button type="button" class="btn" style="background-color: RoyalBlue; color:white; font-weight: bold" value="'+ valor.codigo +'" id="' + valor.STATUS +'">'+ valor.STATUS +'</button></td>';
				}
				
				else if(valor.STATUS == "VENCIDO")
				{
					atividades += '<td><button type="button" class="btn" style="background-color: Red; color:white; font-weight: bold" value="'+ valor.codigo +'" id="' + valor.STATUS +'">'+ valor.STATUS +'</button></td>';
				}
				
				else if(valor.STATUS == "PENDENTE")
				{
					atividades += '<td><button type="button" class="btn" style="background-color: DarkOrange; color:white; font-weight: bold" value="'+ valor.codigo +'" id="' + valor.STATUS +'">'+ valor.STATUS +'</button></td>';
				}
				
				else if(valor.STATUS == "INICIADO_VENCIDO")
				{
					atividades += '<td><button type="button" class="btn" style="background-color: SeaGreen; color:white; font-weight: bold" value="'+ valor.codigo +'" id="' + valor.STATUS +'">'+ valor.STATUS +'</button></td>';
				}
				
				
				//atividades += '<td><button class="btn-secondary" id="'+ valor.codigo +'">Detalhes</button></td>';
				atividades += '</tr>';
			});
			
			$('#registros-atividades').html(atividades);
<div class="row">
				
				<!-- INÍCIO DA DIV COM O FORMULÁRIO DE PESQUISA -->
				
				<div class="col-lg-12" id="pesquisa">
				
					<form id="formulario-consulta"> <!-- FORMULÁRIO DE PESQUISA -->
						<div class="form-inline">			
						
								<div class="row">
								
									<div class="col-lg-10 col-lg-offset-1">
										<div class="col-lg-2 form-group">
											<button class="btn btn-sm btn-success" id="botao-resumo" style="margin-top: 0">Resumo por Status</button>
										</div>

										<div class="col-lg-4 form-group">
											<h5>Filtrar:</h5>
											<div class="radio">
												<select name="prioridade" id="prioridade" class="input-sm form-control">
													<option  value="Todos" selected>TODOS</option>
													<option  value="Comum">COMUM</option>
													<option  value="Extra">EXTRA</option>
													<option  value="Urgente">URGENTE</option>
												</select>
											</div>
										</div>
										
										<div class="col-lg-2 form-group">
											<h5>Filtrar por data de:</h5>
											<div class="radio">
												<select name="data" id="data" class="input-sm form-control">
													<option  value="inicio">INÍCIO</option>
													<option  value="finalizacao">FINALIZAÇÃO</option>
													<option  value="vencimento" selected>VENCIMENTO</option>
												</select>
											</div>
																																		
										</div>
										
										<div class="col-lg-4 form-group">
											<h5>Filtrar por período:</h5>
											De: <input type="date" name="dataInicial" id="dataInicial" class="input-sm form-control" style="width:40%;">
											Até: <input type="date" name="dataFinal" id="dataFinal" class="input-sm form-control" style="width:40%;">
																																								
										</div>	
									</div>
								</div>

							
							<div class="row">
								
								<div class="col-lg-10 col-lg-offset-1">
										
									<div class="">
									
										<div class="col-lg-2 form-group">
											<div class="radio">
												<h5>COD</h5>
												<select  name="cod" class="input-sm form-control">
												<option></option>
												<?php
													while($linha_cod = mysqli_fetch_assoc($lista_cod))
													{
												?>	
													<option value="<?php echo $linha_cod["COD"]; ?> ">	
														<?php echo $linha_cod["COD"]; ?>
													</option>

												<?php
													}
												?>
												</select>
											</div>
										</div>	
										
										<div class="col-lg-2 form-group">
											<div class="radio">
												<h5>Empresa</h5>
												<select name="empresas" id="empresas" class="input-sm form-control" style="width: 100%">
												<option></option>
													<?php
													while($linha_empresas = mysqli_fetch_assoc($lista_empresas))
													{
													?>	
														<option value="<?php echo $linha_empresas["EMPRESAS"]; ?> ">	
															<?php echo $linha_empresas["EMPRESAS"]; ?>
														</option>

													<?php
														}
													?>
												</select>
											</div>
										</div>	
											
										<div class="col-lg-2 form-group">
											<div class="radio">
												<h5>Tributação</h5>
												<select name="tributacao" id="tributacao" class="input-sm form-control">
												<option></option>
												<?php
													while($linha_tributacao = mysqli_fetch_assoc($lista_tributacao))
													{
												?>	
													<option value="<?php echo $linha_tributacao["TRIBUTACAO"]; ?> ">	
														<?php echo $linha_tributacao["TRIBUTACAO"]; ?>
													</option>

												<?php
													}
												?>
												</select>
											</div>
										</div>
										
										<div class="col-lg-2 form-group">
											<div class="radio">
												<h5>Atividade</h5>
												<select name="atividade" id="atividade" class="input-sm form-control">
												<option></option>
													<?php
														while($linha_atividade = mysqli_fetch_assoc($lista_atividade))
														{
													?>	
													<option value="<?php echo $linha_atividade["TIPO_ATIVIDADE"];?>">	
														<?php echo $linha_atividade["TIPO_ATIVIDADE"]; ?>
													</option>

													<?php
														}
													?>
												</select>
											</div>
										</div>
										
										<div class="col-lg-1 col-lg-offset-1 form-group">
											<div class="radio">
												<h5>Status</h5>
												<select name="status" id="status" class="input-sm form-control">
												<option></option>
													<?php
														while($linha_status = mysqli_fetch_assoc($lista_status))
														{
													?>	
													<option value="<?php echo $linha_status["STATUS"]; ?> ">	
														<?php echo $linha_status["STATUS"]; ?>
													</option>

													<?php
														}
													?>
												</select>
											</div>
										</div>
										
										<div class="col-lg-1 col-lg-offset-1 form-group">
											<h5>Pesquisar</h5>
											<input name="enviar" id="enviar" class="btn btn-sm btn-primary btn-block" type="submit" value="Enviar">
											
										</div>
																				
									</div>
								</div>														
							</div>
						</div>
					</form>
				</div>	
				
			</div>			
						

						
			<div class="row">
				
				<!-- DIV QUE EXIBE O RESULTADO DA PESQUISA DO FORMULÁRIO -->
				
				<div class="col-lg-10 col-lg-offset-1" id="resultado-pesquisa">
										
					
					<!-- DIV QUE EXIBE AS INFORMAÇÕES DE RETORNO DA CONSULTA -->
					
					<div class="col-lg-12" id="exibicao">
						
						<!-- TABELA QUE EXIBE DINAMICAMENTE COM O PHP OS RESULTADOS DA CONSULTA AO BANCO -->
						
						<table class="table table-bordered table-condensed table-striped table-hover" id="resultado-exibicao">
							
							<thead>
								<tr><th>Código</th><th>COD</th><th>EMPRESA</th><th>TRIBUTAÇÃO</th><th>TIPO DE ATIVIDADE</th><th>DT.VENC</th><th>DT.INÍCIO</th><th>DT.FIM</th><th>STATUS</th><!--<th>DETALHES</th>--></tr>
							</thead>
							
							<tbody id="registros-atividades">
								
								
								
							</tbody>
							
							
						
						</table>
												
						
					</div>
					
					
				</div>
				
			</div>
			
			<!-- DIV PARA EXIBIÇÃO DO RETORNO DA CONSULTA DOS CAMPOS DETALHES E FEEDBACK -->
			
			<div class="row" id="detalhesfeedback">
				
				<!--DIV QUE EXIBE O CAMPO DETALHES COM O RETORNO DA CONSULTA -->
				
				<div class="col-lg-5 col-lg-offset-1 panel panel-primary" id="detalhes">
					<div class="panel-heading">
						<h4 class="panel-title">OBSERVAÇÕES</h4>
					</div>
							
							
					<div class="panel-body" id="espaco-detalhes">
						
					</div>
											
				</div>
				

				<!--DIV QUE EXIBE O CAMPO FEEDBACK COM O RETORNO DA CONSULTA -->
				
				<div class="col-lg-5 panel panel-primary" id="feedback">
					
					<div class="panel-heading">
						<h4 class="panel-title">FEEDBACK DA GERÊNCIA / RESPONSÁVEL SETOR</h4>
					</div>
							
							
					<div class="panel-body" id="espaco-feedback">
						
					
						
					</div>
											
				</div>
				
				<!-- DIV COM OS BOTÕES QUE EXECUTAM AÇÕES NO BANCO -->
				
				<div class="col-lg-10 col-lg-offset-1" id="botoes-detalhes-feedback">
								
					<a class="btn btn-md btn-primary" href="#" >Inserir Observações</a></button>
					<a class="btn btn-md btn-success" href="#" >Reabrir Atividades</a></button>
					<!--<button class="btn btn-md btn-danger"><a href="#" data-toggle="modal" data-target="#modal-reabrir-atividades">Sem Movimento/Arquivo</a></button>-->
					
				</div>
				
				<!--
				
				<div class="modal" tabindex="-1" id="modal-autorizar">
					<div class="modal-dialog">
						<div class="modal-content">
							<div class="modal-header">
								<button class="close"
										aria-label="close"
										data-dismiss="modal">
									<span aria-hidden="true">&times;</span>
								</button>
								<h4 class="modal-title">Você tem certeza que quer realizar esse procedimento ?</h4>
							</div>
							
							<div class="modal-body">
															
								<a class="btn btn-lg" value="confirmar" name="confirmar" id="confirmar" style="background-color:CornflowerBlue; color: white; font-weight: bold">ALTERANDO O STATUS DA ATIVIDADE</a> <!-- &nbsp <a class="btn btn-lg btn-danger" value="NAO" name="nao" id="negar">NAO</a> 
						
							</div>
							
						</div>
					</div>
				</div>
			
				-->
				
			</div>
			
			
			
		</div>
		
		<!-- SCRIPTS -->
		
		
		<script src="_jquery/jquery-3.2.1.min.js"></script> <!-- ARQUIVO JQUERY -->
		<script src="_bootstrap4.1.1/js/bootstrap.min.js"></script>
		<script src="_scripts/interface-script.js"></script>
		
		
		
		
	
		
</body> <!-- FIM DO BODY -->
</html> <!-- FIM DO HTML -->

<?php
	// Fechando Conexão
	
	mysqli_close($conecta);
	
	
?>

<!-- ARQUIVO PHP QUE REALIZA O SELECT NO BANCO DE DADOS interface-resultado-pesquisa.php -->

<?php 
	
	
	require_once("conexao-com-banco.php"); // CHAMANDO O ARQUIVO DE CONEXÃO AO BANCO

	
		
	// CONSULTA GERAL DO BANCO  QUE RETORNA O RESULTADO DA CONSULTA DA PÁGINA INTERFACE.PHP 
		
	session_start();	
	
			
			//PREENCHE AS VARIÁVEIS COM OS DADOS VINDOS DOS CAMPOS DO FORMULÁRIO
			
			$pegaropcao   = utf8_decode($_POST["prioridade"]);
			$tipodedata = $_POST["data"];
			$dataInicial = $_POST["dataInicial"];
			$dataFinal  = $_POST["dataFinal"];
			$cod = utf8_decode($_POST["cod"]);
			$empresas   = utf8_decode($_POST["empresas"]);
			$tributacao = utf8_decode($_POST["tributacao"]);
			$atividade  = utf8_decode($_POST["atividade"]);
			
			$status = utf8_decode($_POST["status"]);
			$responsavel = $_SESSION["nome"];
			
			
			
			//VERIFICA QUAL É O TIPO DE ATIVIDADE ENTRE AS EXTRAS, URGENTES OU COMUM
					
			if($pegaropcao == "Comum")
			{
				$tipodeatividade = " AND EXTRA_URGENTE_COMUM  = 'C'";
			
			}
			else if($pegaropcao == "Urgente")
			{
				$tipodeatividade = " AND EXTRA_URGENTE_COMUM  = 'U'";
			
			}	
			else if($pegaropcao == "Extra")
			{
				$tipodeatividade = " AND EXTRA_URGENTE_COMUM  = 'E'";
			
			}	
			else 
			{
				$tipodeatividade = " AND EXTRA_URGENTE_COMUM  <> 'N'";
			
			}	
			
			
			//IF PARA VERIFICAR POR QUAL TIPO DE DATA O BANCO IRÁ FILTRAR 
						
			if (isset($dataInicial) AND isset($dataFinal)) 
			{
				$teste = "Entrou no IF";
							
				if($tipodedata == "vencimento")
				{
					$variavel = " AND DT_VENCIMENTO BETWEEN '$dataInicial' AND '$dataFinal' ORDER BY DT_VENCIMENTO";	
				}
				else if ($tipodedata == "finalizacao")
				{
					$variavel = " AND DT_FIM BETWEEN  '$dataInicial' AND '$dataFinal' ORDER BY DT_FIM";
				}
				else if($tipodedata == "inicio")
				{
					$variavel = " AND DT_INICIO BETWEEN '$dataInicial' AND '$dataFinal' ORDER BY DT_INICIO";
				}
				
			}
			//(ESSE ELSE QUE É A PARTE DO ERRO) -------------------------AQUI---------------------------------
			else  
			{		
				
				$variavel = " ORDER BY DT_VENCIMENTO asc";
			}			
			
		
			
			//REALIZA A CONSULTA NO BANCO DE DADOS COM OS DADOS VINDOS DO FORMULÁRIO
			
			$pesquisar    = "SELECT COD, EMPRESAS, TRIBUTACAO, TIPO_ATIVIDADE, STATUS, DETALHES, FEEDBACK, DATE_FORMAT(DT_VENCIMENTO, '%d/%m/%Y' ) AS DT_VENCIMENTO, DATE_FORMAT(DT_INICIO, '%d/%m/%Y' ) AS DT_INICIO, DATE_FORMAT(DT_FIM, '%d/%m/%Y') AS DT_FIM, codigo FROM tbl_atividades";
			$pesquisar    .= " WHERE COD like '%$cod%' AND EMPRESAS like '%$empresas' AND TRIBUTACAO like '%$tributacao' AND TIPO_ATIVIDADE like '%$atividade' AND RESPONSAVEL = '$responsavel' AND STATUS like '%$status' $tipodeatividade $variavel";
										
			$operacao_consulta = mysqli_query($conecta, $pesquisar) or die("Erro na conexão com banco de dados");	
			
			
			
				$retorno = array();
				while($linha = mysqli_fetch_object($operacao_consulta))
				{					
						$retorno[] = $linha;		
				} 	
				
			
				echo json_encode($retorno);
				
					
		
?>

SEE BELOW THE IMAGE OF THE ERROR IN PHP FILE

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

Note in the second image that there is a red marked part in which is the output of the value of the variable that was configured within the ELSE.

BELOW, THE IMAGE WITH THE RESULT OF THE QUERY, WHICH EXECUTES THE IF, WHICH USED THE $_POST THAT YOU ARE SAYING IS NOT RECEIVING VALUES.

inserir a descrição da imagem aqui

  • Makes a var_dump($pesquisar); and check how your select gets

2 answers

3


As they say all the errors in your script, the indices are not defined.

Note that all lines showing errors are related to $_POST:

print

What you need to do is check the attributes name of input of your form and check the method if it is defined as post.

The service of if mentioned is just check if your page has received the information:

if (isset($dataInicial) AND isset($dataFinal))

And here is precisely the root of the problem! The function isset() of PHP returns true even in cases where the variable is empty: $foo = ''. Which is exactly what’s happening on your form!

One of the solutions is to exchange the isset() for empty(). Relating directly to your code, we can do so:

$dataInicial = !empty($_POST["dataInicial"]) ? $_POST["dataInicial"] : null;
$dataFinal  = !empty($_POST["dataFinal"]) ? $_POST["dataFinal"] : null;

With the state null in those variables, their if will work as expected, since the isset() returns false if the variable is null.


See a simple form of check what and which method is coming from the form:

<?php
echo '<pre>';
echo 'Informações via método POST:'.PHP_EOL;
print_r($_POST);
echo 'Informações via método GET:'.PHP_EOL;
print_r($_GET);
echo '</pre>';
die();

Recommended reading: PHP: $_POST

Recommended reading: PHP: isset()

Recommended reading: PHP: Empty()

  • Yes, I understood brother. But the data coming from the POST is being received. Until the IF condition is executed and this IF condition uses the same data that comes from the POST. I will update the code I posted here, with the code in HTML and Java used.

  • @Thiagopetherson No. They are not being received! If they were received, PHP would not have set index. Note that I added a small script for you to check what you are getting on your page.

  • I edited the code for you to visualize better. Lilespry, then as the IF condition is executed and the query returns me the result of the query ?

  • @Thiagopetherson has some contact information in my profile. Call in any of them that I will help you with your code. Unfortunately, the way it is in the question can not reproduce...

-1

Good morning.

The only mistake I saw in your code was not treating the $_POST. It will always keep this error if you do not submit any post. What can be done are these conditions:

$pegaropcao   = (isset($_POST["prioridade"]) && $_POST["prioridade"] != "") ? utf8_decode($_POST["prioridade"]) : "";
    $tipodedata = (isset($_POST["data"]) && $_POST["data"] != "") ?  $_POST["data"] : "";
    $dataInicial = (isset($_POST["dataInicial"]) && $_POST["dataInicial"] != "") ?  $_POST["dataInicial"] : "";
    $dataFinal  = (isset($_POST["dataFinal"]) && $_POST["dataFinal"] != "") ?  $_POST["dataFinal"] : "";
    $cod = (isset($_POST["cod"]) && $_POST["cod"] != "") ?  utf8_decode($_POST["cod"]) : "";
    $empresas   = (isset($_POST["empresas"]) && $_POST["empresas"] != "") ?  utf8_decode($_POST["empresas"]) : "";
    $tributacao = (isset($_POST["tributacao"]) && $_POST["tributacao"] != "") ?  utf8_decode($_POST["tributacao"]) : "";
    $atividade  = (isset($_POST["atividade"]) && $_POST["atividade"] != "") ?  utf8_decode($_POST["atividade"]) : "";

    $status = (isset($_POST["status"]) && $_POST["status"] != "") ?  utf8_decode($_POST["status"]) : "";
    $responsavel = (isset($_SESSION["nome"]) && $_SESSION["nome"] != "") ?  $_SESSION["nome"] : "";

What I did was check if $_POST exists, if it does not exist returns empty.

  • If you have actually read the whole code of it you should have noticed that if no data comes in the post enters an Else. So with this will not push anything, just solve the mistakes if nothing comes by the post. And utf8_decode() is part of his code tbm, if there is value he of this command (I don’t know what value comes then I kept what he did himself).

  • "- if no data comes in the post enters an Else" then of the line 85 down does not matter, either, whether came data or not?! Will mount a query full of like '%'... By the way, don’t misunderstand me! I just tapped in because I thought it would be useful. I’m sorry!

  • Without delay, but looking at my complete code instead of theories, no offense, but could you please point out where my mistake is? Be in PHP, Mysql query, HTML in Javascript ... Please. Humbly speaking.

  • I edited the post and added an image in which proves that $_POST is arriving yes in the PHP file

  • You even tested putting this code I made in place of yours?

  • If there is no data in the POST in those two variables cited, Lipespry, it doesn’t really matter. Ai performs the ELSE.

  • @Thiagopetherson is. But what about the rest? On line 85 you need the other data, which are also accusing index error. As I said up there, it’s going to be a very messed up query! Despite everything, it’s very difficult to understand all this code. You mixed the file in the snipper and it’s making me a little confused.

  • @Lucasxavier, I put your code and you keep giving the same result.

  • @Lipespry, did you get to see the last image I put in there ? That is the return of the query when the IF condition is executed and there is no need to enter the ELSE. This IF condition is executed using values that came via $_POST. If, as you say, the $_POST is not coming, then the query is executed using such values from $_POST ?

  • @Lipespry and Lucasxavier, I know the code is wrong, so I posted it here. Except that I was waiting for people to analyze the code and see where the error is. I made available the PHP, HTML and Javascript part. The error is in one of these places. I believe it is in PHP.

  • @Lucasxavier, but it’s already improved. Now it’s only showing an error saying that the variable is not defined. Notice: Undefined variable: variable in C: wamp64 www project-do-sistema-interno-jca interface-result-search.php on line 84

  • Remove the Else below the comment: (ESSE ELSE QUE É A PARTE DO ERRO) and glue only that line: $variavel = " ORDER BY DT_VENCIMENTO asc"; below the comment: IF PARA VERIFICAR POR QUAL TIPO DE DATA O BANCO IRÁ FILTRAR

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.