Alert appearing at the wrong time

0

I made a php code where the first part of it is to go through the login.php page. and for this I put an alert to warn when the login and password are incorrect. for that I put an If and an else and left the alert inside the Else, but when entering the page the first thing that does is show the window of the alert with the massage that I placed and whenever I update the page the window of the alert appear, being that I want to make the alert appear only when the login or password is incorrect. below the codes used.

Login.php

<html>
<head>
	<meta charset="UTF-8">
    <script>
var modal = document.getElementById('id01');

window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
var modal = document.getElementById('id02');


window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

function funcao(x) {
    x.style.background = "#B22222";
}
</script>

</head>
<body id="imgpos">
    <center>
  <h2 title="nao fique parado!">Sistema Controle de Produtos</h2>

<button onclick="document.getElementById('id01').style.
display='block'" style="width:auto;">Login</button>
<button onclick="document.getElementById('id02').style.
display='block'" style="width:auto;">Cadastro</button>
</center>
	<div id="id01" class="modal">
  
  <form class="modal-content animate" action ="" method = "post" >
    <div class="imgcontainer">
      <span onclick="document.getElementById('id01').style.display='none'" class="close" title="fechar">&times;</span>
     <img src="4ad.png" alt="Avatar" class="avatar">
    </div>
    <div class="container">
      <label><b>Login:</b></label>
      <input type="text" placeholder="Digite seu usuario" name="login" required onfocus ="funcao(this)">

      <label><b>Senha:</b></label>
      <input type="password" placeholder="Digite sua senha" name="senha" required required minlength="8" maxlength="8" onfocus ="funcao(this)">
        
      <button type="submit">Entrar!</button>
    </div>

    <div class="container" style="background-color:#7FFFD4">
      <center>
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
      </center>
    </div>
  </form>
</div>
<div id="id02" class="modal">
  
  <form class="modal-content animate" action ="evento2.php?cadastro=true" method = "post" >
    <div class="imgcontainer">
      <span onclick="document.getElementById('id02').style.display='none'" class="close" title="voltar">&times;</span>
     <img src="25.png" alt="Avatar" class="avatar">
    </div>
    <div class="container">
      <label><b>Login:</b></label>
      <input type="text" placeholder="Digite o usuario desejado" name="login1" required onfocus ="funcao(this)">

      <label><b>Senha:</b></label>
      <input type="password" placeholder="Digite a senha desejada" name="senha1" required minlength="8" maxlength="8" onfocus ="funcao(this)">
        
      <button type="submit">Cadastrar!</button>
    </div>

    <div class="container" style="background-color:#7FFFD4">
      <center>
      <button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">voltar</button>
      </center>
    </div>
  </form>
</div>
<h3 align="center">&copy Amem!</h3>
<?php
include_once "conexao.php";
if(isset($_POST['login']))$login = $_POST['login'];
if(isset($_POST['senha']))$senha = $_POST['senha'];
$sql="select * from funcionario where nome='$login' and senha='$senha'";
$result=mysql_query($sql,$con);
$res=mysql_num_rows($result);
if($res){
	$linha=mysql_fetch_array($result);
	session_start();
	$_SESSION['id']=$linha['id_funcionario'];
	$_SESSION['nome']=$linha['nome'];
	echo "<script> window.location='index.php'</script>";		
}else{
    echo "<script>alert('Login ou Senha invalidos')</script>";
}
?>
</body>
</html>

index.php

<?php
 session_start();
 if(isset($_SESSION['id'])==0 and isset($_SESSION['nome'])==0){
  echo "<script> window.location='login.php'</script>";
}else{
  $nome=$_SESSION['nome'];
  echo "<h3>usuario: $nome <a href='login.php'>sair</a></h3>";
}
?>
<HTML>
  <HEAD>
    <script type="text/javascript">
function valida_preco() {
   var num = document.getElementById('preco').value;
   if ( isNaN( num ) ) { // isNaN = is not a number
      alert('Não é um número!');
      return false;
   }
   return true; // prossegue o envio
}
</script>
    <meta charset="utf-8">
     <TITLE>Cadastros</TITLE>

 <script type="text/javascript" src="jquery-3.2.1.js"></script>
 <script src="jquery.maskMoney.js" type="text/javascript"></script>
<script type="text/javascript">
  $(document).ready(function(){
$("#horario tbody tr:odd").addClass("zebraum");
});
  $(document).ready(function(){
$("#horario tbody tr:even").addClass("zebradois");
});
    $(function(){
        $("#valor").maskMoney();
    })
</script>
</HEAD>
<BODY id="imgpos">
<center>
  <h2 title="nao fique parado!">Controle de Estoque!</h2>

<button onclick="document.getElementById('id01').style.
display='block'" style="width:auto;">Cadastra-se</button>
<button onclick="document.getElementById('id02').style.
display='block'" style="width:auto;">Registros</button>
</center>
<div id="id01" class="modal">
  
  <form class="modal-content animate" action ="evento.php?cadastro=true" method = "post" >
    <div class="imgcontainer">
      <span onclick="document.getElementById('id01').style.display='none'" class="close" title="fechar">&times;</span>
     <img src="5534.jpg" alt="Avatar" class="avatar">
    </div>
    <div class="container">
      <label><b>Produto:</b></label>
      <input type="text" placeholder="Digite o nome do Produto" name="produto" required onfocus ="funcao(this)">

      <label><b>Preço:</b></label>
      <input type="text" id="valor" placeholder="R$..." name="preco" required onfocus ="funcao(this)">
        
      <button type="submit">Cadastrar!</button>
    </div>

    <div class="container" style="background-color:#7FFFD4">
      <center>
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
      </center>
    </div>
  </form>
</div>
    <div id="id02" class="modal">

    <form class="modal-content animate" action ="evento.php?cadastro=true" method = "post" >
        <div class="imgcontainer">
      <span onclick="document.getElementById('id02').style.display='none'" class="close" title="Voltar">&times;</span>

    </div>

    <div class="container">
      
    <div class="container" style="background-color:#7FFFD4">
      <center> <h2>Lista de Produtos 
</h2></center>
 <table border="2" id='horario'>
 <thead>
<tr>
  <th>id</th>
  <th>Produto</th>
  <th>Preço</th>
  <th>Funcionário</th>
  <th>Alterar</th>
  <th>Excluir</th>
</tr>
<style type="text/css">
  tbody tr:hover{background-color:#555} 

</style>
</thead>
<tfoot>
    <tr>
        <td colspan="6"><center><script language=javascript type="text/javascript">
    dayName = new Array ("domingo", "segunda", "terça", "quarta", "quinta", "sexta", "sábado")
monName = new Array ("janeiro", "fevereiro", "março", "abril", "maio", "junho", "agosto", "outubro", "novembro", "dezembro")
now = new Date
document.write (" Hoje é " + dayName[now.getDay() ] + ", " + now.getDate () + " de " + monName [now.getMonth() ]   +  " de "  +     now.getFullYear () + "   ")
document.write ( + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() )
</script></center></td>
    </tr>
</tfoot>
<center>
 <?php
            include_once "conexao.php";
            $sql = "select p.codigo, p.nome as np, p.preco, c.nome as nf from funcionario as c join produto as p on
            c.id_funcionario=p.id_funcionario";
            $result = mysql_query($sql,$con);
            if($result){
            while($linha = mysql_fetch_array($result)){
?>

<tbody id="horario">
       <tr>
           <td id='p3'> <?php  echo $linha['codigo'];?></td>
           <td> <?php echo $linha['np'];?></td>
           <td id='p4'> <?php echo "R$". $linha['preco'];?></td>
           <td> <?php echo $linha['nf'];?></td>       
           <td> <?php echo "<a id='p1' href = editar.php?editar=".$linha['codigo']." >editar </a>";?></td>
           <td> <?php echo "<a id='p2' href = evento.php?deletar=".$linha['codigo'].">excluir</a>";?></td>
       </tr>
</tbody>

<?php
          }//fim do while
          }//fim do if  
          mysql_close($con);
?>
</table> 
    <center>
      <button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn">voltar</button>
       </center>
    </div>
  </form>
</div>
<script>
var modal = document.getElementById('id01');

window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
var modal = document.getElementById('id02');


window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

function funcao(x) {
    x.style.background = "#B22222";
}
</script>
<h3 align="center">&copy Amem!</h3>
<BR>

</BODY>
</HTML>

connection.php

<HTML>
<HEAD>
 <TITLE>Conexao</TITLE>
</HEAD>
<BODY>
<?php
  $host="localhost";
  $login="root";
  $senha="";
  $banco="controle_de_estoque";

  $con=mysql_connect($host,$login,$senha)or die("Erro ao conecta!".mysql_error());
  $sql="create database if not exists ".$banco;
  mysql_query($sql,$con);
  mysql_select_db($banco,$con);
  $sql = "create table if not exists funcionario(
  id_funcionario int(8) auto_increment,
  nome varchar(100) not null,
  senha varchar(50) not null,
  primary key(id_funcionario))";
  mysql_query($sql,$con);
  $sql="create table if not exists produto(codigo int(8) auto_increment,
  nome varchar(100) not null, preco varchar(15) not null, id_funcionario int(8) not null,
  primary key(codigo), foreign key(id_funcionario) references funcionario(id_funcionario))";
  mysql_query($sql);
?>

</BODY> 
</HTML>

edit.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
    <?php
    include_once 'conexao.php';
    $sql='select * from produto where codigo='.$_GET['editar'];
    $result=mysql_query($sql,$con);
    $linha=mysql_fetch_array($result);
    ?>
    
<script type="text/javascript" src="jquery-3.2.1.js"></script>
 <script src="jquery.maskMoney.js" type="text/javascript"></script>
 <script type="text/javascript">
 $(function(){
        $("#valor").maskMoney();
    })
</script>

<body>
<center>
<div id="id01" class="modal" >
    </center>
  <form class="modal-content animate"<?php echo "<form action= 'evento.php?editar=".$linha['codigo']."'method='post'";?>>
    <div class="imgcontainer">
      <span onclick="window.location='index.php'" class="close" title="fechar">&times;</span>
     <img src="5534.jpg" alt="Avatar" class="avatar">
    </div>
    <div class="container"><br>
      Produto:<br>
         <input type="text" name="produto" value="<?php echo $linha['nome'];?>" required><p></p>
        Preço:<br>
         <input type="text" id="valor" name="preco" value="<?php echo $linha['preco'];?>" required><p></p>
         <br>
      <button type="submit">Editar</button>
    </div>
    <div class="container" style="background-color:#7FFFD4">
        <center>
      <button type="button" onclick="window.location='index.php'" class='cancelbtn'>Cancel</button>
        </center>
    </div>
  </form>
</div>
</body>
</html>

event.php

<?php
session_start();
 if(isset($_SESSION['id'])==0 and isset($_SESSION['nome'])==0){
  echo "<script> window.location='login.php'</script>";
}else{
  $userId=$_SESSION['id'];
  $nome=$_SESSION['nome'];
}

 include_once'conexao.php';
 if(isset($_POST['produto']))$atrProduto = $_POST['produto'];
 if(isset($_POST['preco']))$atrPreco = $_POST['preco'];
 if(isset($_GET['cadastro']))
 {


$sql = sprintf("INSERT INTO 'produto' SET 'nome' = \"%s\", 'preco' = \"%s\", 'id_funcionario' = \"%d\";",
    $atrProduto,
    $atrPreco,
    $userId);

 mysql_query($sql,$con);
 echo "<script>alert('Produto cadastrado com sucesso!')</script>";
 }
 if(isset($_GET['deletar'])){
 $sql = "delete from produto where codigo = ".$_GET['deletar'];
 mysql_query($sql,$con);
 echo "<script>alert('Produto deletado com sucesso!')</script>";
 }
 if(isset($_GET['editar'])){
 $sql = "update produto set nome= '".$atrProduto."',preco='".$atrPreco."', id_funcionario=".$userId." where codigo=".$_GET['editar'];
 mysql_query($sql,$con);
 echo"<script> alert('Produto atualizado com sucesso')</script>";
 }
 echo"<script>window.location='index.php'</script>";

Someone could help me find my error, because the alert always works as soon as I enter the page.

    
asked by anonymous 09.01.2018 / 21:43

1 answer

0

Dude, make those changes to your code.

if($_POST['login'] && $_POST['senha']){
      $email = $_POST['login'];
      $password = $_POST['senha'];
      $sql="SELECT * FROM funcionario WHERE email='$email' AND senha='$password'";
      $result=mysql_query($sql,$con);
      $res=mysql_num_rows($result);
      if($res){
        $linha=mysql_fetch_array($result);
        session_start();
        $_SESSION['id']=$linha['id_funcionario'];
        $_SESSION['nome']=$linha['nome'];
        echo "<script> window.location='index.php'</script>";   
      }else{
        echo "<script>alert('Login ou Senha invalidos')</script>";
      }
    }
    
09.01.2018 / 22:12