Update edits all information instead of just one specific, when I put Where to an edit specifies nothing is edited, what to do?

Asked

Viewed 264 times

-2

I’m making a code where the person adds records on the site that are shown to her in list on a table, on each line there’s a button to edit, when I edit some information all other records are changed, When I put a Where at the end of the update code and try to do some editing nothing works and no information is edited, could anyone help me with that? I’ve gone through all the code and I can’t find the problem. Below are the 2 codes:

Code to view records and edit them:

<body>
<div class="container">
<!--Modal-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">

        <div class="modal-content">
            <div class="modal-header">
                <h1>Adicione uma pessoa para que possa ter o seu registro salvo</h1>
            </div>
            <div class="modal-body">
                <!--- Modal com form para se fazer a edição das informações -->
                <form class="form-group well" action="receberegistro.php?acao=alterar" method="POST">
                        <input type="hidden" name="codreg" value="<?php echo $codreg ?>">
                        <input type="text" name="nome" class="span3" value="
<?php echo $nome;?>" required placeholder="Nome" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input type="tel" name="tel" class="span3" placeholder="Número de telefone" required value="<?php echo $tel;?>" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input type="tel" name="cel" class="span3 pull-right" placeholder="Número de celular" required value="<?php echo $cel;?>" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input type="text" name="ende" class="span3" value="
<?php echo $ende;?>" required placeholder="Endereço" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <textarea placeholder="Orçamento/Serviço" class="span3" required name="serv"><?php echo $serv;?></textarea><br><br>
                        <button type="submit" class="btn btn-success btn-large" name="adicionar" style="height: 35px">Adicionar registro</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                <button type="button" class="btn btn-default">Teste</button>
            </div>
        </div>
    </div>
</div>
<div class="row">
<h2>Lista de pessoas registradas</h2><br>
    <form method="POST" action="">
        <input type="text" name="pesquisa" placeholder="Pesquisar pessoas" class="span4" style="margin-bottom: -2px; height: 25px;">
        <button type="button" name="pesquisar" class="btn btn-large" style="height: 35px;">Pesquisar</button>
    </form>
    <table border="1px" bordercolor="gray" class="table table-stripped">
        <tr>
            <td>Nome</td>
            <td>Telefone Fixo</td>
            <td>Celular</td>
            <td>Endereço</td>
            <td>Orçamento/Serviço</td>
            <td>Data</td>
            <td>Hora</td>
            <td>Ação</td>
        </tr>
            <?php   
                include_once('conectar.php');

                $consulta = mysql_query("select * from registro") or die (mysql_error());
                if(!empty($_POST['pesquisa']))
                {
                    $pesquisa = $_POST['pesquisa'];
                    $consulta = mysql_query("select * from registro '$pesquisa%'") or die(mysql_error());
                }
                while($dados = mysql_fetch_array($consulta))
                {
            ?>
        <tr>
            <td><?php echo $dados['nome']; ?></td>
            <td><?php echo $dados['tel']; ?></td>
            <td><?php echo $dados['cel']; ?></td>
            <td><?php echo $dados['ende']; ?></td>
            <td><?php echo $dados['serv']?></td>
            <td><?php echo $dados['data']; ?></td>
            <td><?php echo $dados['hora']; ?></td>
            <td>
                <a href="?acao=excluir&codreg=<?php echo $dados['codreg'];?>" onclick="return confirm('Deseja realmente excluir este registro?');"><button class="btn btn-danger" type="button" name="excluir">Excluir</button></a>

                <a href="#myModal?acao=dados&codreg=<?php echo $dados['codreg'];?>"><button type="button" name="alterar" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Editar</button></a>
                </a>
            </td>
        </tr>
            <?php
                }
            ?>
    </table>
</div>
<a href="registro.php"><button type="button" class="btn" name="voltar">Voltar</button></a>
</div>
</div>
</body>

Code that receives the records, sends them to the comic book, changes them, etc:

<?php
$codreg = "";
$nome = "";
$tel = "";
$cel = "";
$ende = "";
$serv = "";
$data = "";
$hora = "";

if(!empty($_GET['acao']))
{
include_once("conectar.php");

$acao = $_GET['acao'];

if($acao == "cadastrar")
{
    $nome = $_POST['nome'];
    $tel = $_POST['tel'];
    $cel = $_POST['cel'];
    $ende = $_POST['ende'];
    $serv = $_POST['serv'];
    $data = date('d-m-y');
    $hora = date('h:i:s');

    $sql = mysql_query("insert into registro (nome, tel, cel, ende, serv, data, hora) values ('$nome','$tel','$cel','$ende','$serv','$data','$hora')") or die (mysql_error());

    echo "<script>alert('Dados cadastrados!'); window.location='registro.php';</script>";
}
else if($acao == "excluir")
{
    $codreg = $_GET['codreg'];
    $sql = mysql_query("delete from registro where codreg = '$codreg'") or die (mysql_error());
    header("location:consultaregistro.php");
}
else if($acao == "alterar")
{ 
    $codreg = $_POST'codreg'];
    $nome = $_POST['nome'];
    $tel = $_POST['tel'];
    $cel = $_POST['cel'];
    $ende = $_POST['ende'];
    $serv = $_POST['serv'];
    $data = date('d-m-y');
    $hora = date('h:i:s');

    $sql = mysql_query("update registro set 
        nome = '$nome',
        tel = '$tel',
        cel = '$cel',
        ende = '$ende',
        serv = '$serv' where codreg = '$codreg'") or die (mysql_error());

    echo "<script>alert('Dados gravados com sucesso!');window.location='consultaregistro.php';</script>";
}
else if($acao == "dados")
{
        //recebe o valor vindo do formulario
    $codreg = $_GET['codreg'];
    $sql = mysql_query("select * from registro where codreg ='$codreg'") or die (mysql_error());
    $dados = mysql_fetch_array($sql);

    $nome = $dados['nome'];
    $tel = $dados['tel'];
    $cel = $dados['cel'];
    $ende = $dados['ende'];
    $serv = $dados['serv'];
    $data = date('d-m-y');
    $hora = date('h:i:s');

    //envia para o banco
    echo "<script>alert('Dados gravados com sucesso!');window.location='consultaregistro.php';</script>";
}
}

?>
  • I advise you to read this your code is vulnerable to various types of attacks

2 answers

3


Correct that line $codreg = $_POST'codreg']; on the stretch below to $codreg = $_POST['codreg'];

The square bracket is missing [ shortly after $_POST

else if($acao == "alterar")
{ 
$codreg = $_POST'codreg'];
echo $codreg;
echo " alterar<br>";

One more mistake - two closing tags </a>

<a href="#myModal?acao=dados&codreg=<?php echo $dados['codreg'];?>"><button type="button" name="alterar" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Editar</button></a> </a>

More error - the main

that your modal is full of echo, I will quote just one, the value of that input

<input type="hidden" name="codreg" value="<?php echo $codreg ?>">

and when clicking edit opens the modal with all of them null.

More error - that link

<a href="?acao=excluir&codreg=<?php echo $dados['codreg'];?>" onclick="return confirm('Deseja realmente excluir este registro?');"><button class="btn btn-danger" type="button" name="excluir">Excluir</button></a>

¿Should not point to receberegistro.php which is the page that receives the records, sends them to the comic, changes them, etc ?

More error - In the search form the

<button type="button" name="pesquisar"... has to be <button type="submit" name="pesquisar"... who will send the form.

<button type="button" name="pesquisar"... need javascript to invoke form Submit event.

The mistakes are so many that it’s better to start from scratch

And since we are starting from scratch, it is opportune to upgrade from mysql to mysqli, as we all know mysql has been discontinued. Learn more with []

connect php.

$servidor = "localhost";
$usuario = "USUARIO";
$senha = "SENHA";
$dbname = "NOME_DB";

//Cria a conexao
$conn = mysqli_connect($servidor, $usuario, $senha, $dbname);

if(!$conn){
    die("Falha na conexao: " . mysqli_connect_error());
}

Follow the code with proper comments

<?php
//declaração das variaveis
$codreg = "";
$nome = "";
$tel = "";
$cel = "";
$ende = "";
$serv = "";
$data = "";
$hora = "";

//conexão ao banco de dados
include_once('conectar.php');

if(!empty($_GET['acao'])){
   $acao = $_GET['acao'];

   if(($acao == "cadastrar")||($acao == "alterar")){
      $nome = $_POST['nome'];
      $tel = $_POST['tel'];
      $cel = $_POST['cel'];
      $ende = $_POST['ende'];
      $serv = $_POST['serv'];
      $data = date('d-m-y');
      $hora = date('h:i:s');
   }

   if($acao == "cadastrar"){
      $sql = ("insert into registro (nome, tel, cel, ende, serv, data, hora) values ('$nome','$tel','$cel','$ende','$serv','$data','$hora')");
      $resultado = mysqli_query($conn,$sql);
      //echo "<script>alert('Dados cadastrados!'); window.location='registro.php';</script>";
   }else if($acao == "excluir"){
      $codreg = $_GET['codreg'];
      $sql = ("delete from registro where codreg = '$codreg'");
      $resultado = mysqli_query($conn,$sql);
      //header("location:consultaregistro.php");
   }else if($acao == "alterar"){ 
      $codreg = $_POST['codreg'];
      $sql = ("update registro set nome = '$nome',tel = '$tel',cel = '$cel',ende = '$ende',serv = '$serv' where codreg = '$codreg'");
      $resultado = mysqli_query($conn,$sql);
      //echo "<script>alert('Dados alterados com sucesso!'); window.location='consultaregistro.php';</script>";
   }
}
?>
<!-- Biblioteca requerida -->
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<body>


<script>
/********************************************************************************
Função disparada ao clicar no link que abre o modal para edição (Modal Alterar)
valor é uma string com os dados cujo separador é um asteristico.
Com o metodo split separamos essa string para formar os valores a serem inseridos
nos campos do formulário do Modal Alterar
********************************************************************************/

function obterDadosModal(valor) {

   var retorno = valor.split("*");

   document.getElementById('campo').value = retorno[0];   
   document.getElementById('nome').value = retorno[1];    
   document.getElementById('tel').value = retorno[2];
   document.getElementById('cel').value = retorno[3];  
   document.getElementById('ende').value = retorno[4]; 
   document.getElementById('serv').value = retorno[5]; 
}
</script>



<div class="container">
<!--Modal Cadastrar-->
<div class="modal fade" id="myModalCadastrar" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">

        <div class="modal-content">
            <div class="modal-header">
                <h1>Adicione uma pessoa para que possa ter o seu registro salvo</h1>
            </div>
            <div class="modal-body">
                <!--- Modal com form para se fazer inclusão de registro -->
                <form class="form-group well" action="receberegistro.php?acao=cadastrar" method="POST">
                        <input type="text" name="nome" class="span3" value="" required placeholder="Nome" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input type="tel" name="tel" class="span3" placeholder="Número de telefone" required value="" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input type="tel" name="cel" class="span3 pull-right" placeholder="Número de celular" required value="" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input type="text" name="ende" class="span3" value="" required placeholder="Endereço" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <textarea placeholder="Orçamento/Serviço" class="span3" required name="serv"></textarea><br><br>
                        <button type="submit" class="btn btn-success btn-large" name="adicionar" style="height: 35px">Adicionar registro</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                <button type="button" class="btn btn-default">Teste</button>
            </div>
        </div>
    </div>
</div>


<div class="container">
<!--Modal Alterar-->
<div class="modal fade" id="myModalAlterar" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">

        <div class="modal-content">
            <div class="modal-header">
                <h1>Alteração de Registro</h1>
            </div>
            <div class="modal-body">
                <!--- Modal com form para se fazer a edição das informações -->
                <form class="form-group well" action="receberegistro.php?acao=alterar" method="POST">
                        <input id="campo" type="text" id="codreg" name="codreg" value="">
                        <input id="nome" type="text" name="nome" class="span3" value="" required placeholder="Nome" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input id="tel" type="tel" name="tel" class="span3" placeholder="Número de telefone" required value="" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input id="cel" type="tel" name="cel" class="span3 pull-right" placeholder="Número de celular" required value="" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <input id="ende" type="text" name="ende" class="span3" value="" required placeholder="Endereço" style=" margin-bottom: -2px; height: 25px;"><br><br>
                        <textarea id="serv" placeholder="Orçamento/Serviço" class="span3" required name="serv"></textarea><br><br>
                        <button type="submit" class="btn btn-success btn-large" name="editar" style="height: 35px">Alterar registro</button>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                <button type="button" class="btn btn-default">Teste</button>
            </div>
        </div>
    </div>
</div>


<div class="row">
<h2>Lista de pessoas registradas</h2><br>
    <form method="POST" action="receberegistro.php?acao=dados">
        <input type="text" name="pesquisa" placeholder="Pesquisar pessoas" class="span4" style="margin-bottom: -2px; height: 25px;">
        <button type="submit" name="pesquisar" class="btn btn-large" style="height: 35px;">Pesquisar</button> 
        <a href="#myModalCadastrar"><button type="button" name="cadastrar" class="btn btn-primary" data-toggle="modal" data-target="#myModalCadastrar">Cadastrar</button></a>
    </form>
    <table border="1px" bordercolor="gray" class="table table-stripped">
        <tr>
            <td>Nome</td>
            <td>Telefone Fixo</td>
            <td>Celular</td>
            <td>Endereço</td>
            <td>Orçamento/Serviço</td>
            <td>Data</td>
            <td>Hora</td>
            <td>Ação</td>
        </tr>
            <?php

                $consulta = ("select * from registro");

                if(!empty($_POST['pesquisa']))
                {
                    $pesquisa = $_POST['pesquisa'];
                    $consulta = ("select * from registro where nome like '$pesquisa%'");
                }

                $result = mysqli_query($conn, $consulta);

                while($dados = mysqli_fetch_array($result)){
            ?>
        <tr>
            <td><?php echo $dados['nome']; ?></td>
            <td><?php echo $dados['tel']; ?></td>
            <td><?php echo $dados['cel']; ?></td>
            <td><?php echo $dados['ende']; ?></td>
            <td><?php echo $dados['serv']?></td>
            <td><?php echo $dados['data']; ?></td>
            <td><?php echo $dados['hora']; ?></td>
            <td>
                <a href="receberegistro.php?acao=excluir&codreg=<?php echo $dados['codreg'];?>" onclick="return confirm('Deseja realmente excluir este registro?');"><button class="btn btn-danger" type="button" name="excluir">Excluir</button></a>
                //aqui aproveitamos os dados da consulta acima para servirem de parametros na função obterDadosModal e serem utilizados no ModalAlterar
                <a href="#myModalAlterar" onclick="obterDadosModal('<?php echo $dados['codreg'];?>*<?php echo $dados['nome'];?>*<?php echo $dados['tel'];?>*<?php echo $dados['cel'];?>*<?php echo $dados['ende'];?>*<?php echo $dados['serv'];?>')"><button type="button" id='alterar' name='alterar' class="btn btn-primary" data-toggle="modal" data-target="#myModalAlterar">Editar</button></a>

            </td>
        </tr>
            <?php
                }
                mysqli_close($conn);
            ?>
    </table>
</div>
<a href="registro.php"><button type="button" class="btn" name="voltar">Voltar</button></a>
</div>
</div>

</body>
  • Did not work, error persists

  • @Luizoleia, that is, the error is not only the lack of bracket in $codreg = $_POST'codreg']; There are numerous errors as you can see in the edited answer. Anyway there are so many that I thought it best to create from scratch.

-1

Simple, you are sending by POST method, and you are trying to get this information by GET so it is not working UPDATE.

Like this:

$codreg = $_GET['codreg'];

As it should be:

 $codreg = $_POST['codreg'];

and maintain the condition (WHERE).

  • It’s not that, I’ve tried it before, I’ve changed it again, and it still doesn’t work

  • In the form screen where you take the id (codreg ) to send, in this part? <input type="Hidden" name="codreg" value="<? php echo $codreg ?>">

  • Yes, and before that I was trying to pull the id to the $codreg variable by select, but both didn’t work

  • Could post the code used to pull the ID

  • Before I was trying to do so: Php lines in the code of Consultai (which has the edit buttons) before starting html: <? php include_once("receberegistro.php"); $acao = "? acao=register"; //does not change if(!Empty($_GET['codreg'])) //changes according to the code name of the table { $acao = "? acao=change & codreg=$codreg";//changes according to field } ?>

  • In the form for editing the information it looks like this: <form class="form-group well" action="<? php echo $acao; ? >" method="POST">

  • And in the file that changes like this: Else if($acao == "change") { $codreg = $_GET['codreg']; $name = $_POST['name']; $tel = $_POST['tel']; $cel = $_POST['cel']; $Ende = $_POST['Ende']; $Serv = $_POST['Serv']; $data = date(’d-m-y'); $hour = date('h:i:s'); $sql = mysql_query("update record set name = '$name', tel = '$tel', cel = '$cel', Ende = '$Ende', Serv = '$Serv' Where codreg = '$codreg'") or die (mysql_error(); echo "<script>Alert('Recorded data successfully!');window.Location='query.php';</script>"; }

Show 2 more comments

Browser other questions tagged

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