Mysql UPDATE function is editing right, but creates a new empty row at the end of the table

Asked

Viewed 446 times

2

I’m racking my brain here, because function UPDATE works well when used neatly by the terminal or Workbench, but when I do the PHP code via HTML form parameters, it edits neatly too, but creates a new empty line, and creates more and more empty lines each time you edit something. And this does not happen via terminal and workbench. (I thought it had something to do with the date in TIMESTAMP, so I deleted the date field from BD and PHP but the problem continued).

<h1> Editar </h1>
<form method="post" action="<?php require('editar.php'); echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>" >

id: <br><input type="number" name="id_upd">
<br><br>

Nome: <br><input type="text" name="nome_upd">
<br><br>

Localização: <br><input type="text" name="localizacao_upd">

<br><br>

E-mail: <br><input type="text" name="email_upd">
<br><br>

Website: <br><input type="text" name="website_upd">
<br><br>

Gênero:
<input type="radio" name="genero_upd" value="Feminino">Feminino
<input type="radio" name="genero_upd" value="Masculino">Masculino

<br><br>

Mensagem:<br> 
<textarea name="mensagem_upd" rows="10" cols="50"></textarea>
<br>

<input type="submit" name="submit" value="Submit"> 

<?php
$servername = "localhost";
$username = "root";
$password = "*******";
$dbname = "guestbook";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $edit = $id_upd = $nome_upd = $localizacao_upd = $email_upd = $website_upd = $genero_upd = $mensagem_upd = "";

//Inserindo os dados de entrada do usuário recebidos do formulário HTML nas váriaveis
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $id_upd = $_POST["id_upd"];
    $nome_upd = $_POST["nome_upd"];
    $localizacao_upd = $_POST["localizacao_upd"];
    $email_upd = $_POST["email_upd"];
    $website_upd = $_POST["website_upd"];
    $genero_upd = $_POST["genero_upd"];
    $mensagem_upd = $_POST["mensagem_upd"];

}

//Se a entrada do usuário for diferente de "" (vazio) edite o nome para nova entrada.
if($nome_upd != "") {
        //Variável $sql recebe a notação de UPDATE MySQL com parâmetros (os valores serão a entrada do usuário)
        $sql = "UPDATE guestbook SET nome='".$nome_upd."' WHERE id='".$id_upd."'";

        //Preparação de confirmação individual
        $stmt = $conn->prepare($sql);

        //Execução da preparação individual
        $stmt->execute();
}

if($localizacao_upd != "") {
        $sql = "UPDATE guestbook SET localizacao='".$localizacao_upd."' WHERE id='".$id_upd."'";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
}

if($email_upd != "") {
        $sql = "UPDATE guestbook SET email='".$email_upd."' WHERE id='".$id_upd."'";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
}

if($website_upd != "") {
        $sql = "UPDATE guestbook SET website='".$website_upd."' WHERE id='".$id_upd."'";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
}

if($genero_upd != "") {
        $sql = "UPDATE guestbook SET genero='".$genero_upd."' WHERE id='".$id_upd."'";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
}

 if($mensagem_upd != "") {
        $sql = "UPDATE guestbook SET mensagem='".$mensagem_upd."' WHERE id='".$id_upd."'";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
 }
}
catch(PDOException $e) {
    echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Antes de Editar

Depois de Editar

  • Every time you call execute() an update is made.

  • Yes, but it is protected by the if, and if this was the case it was to appear several blank lines and not only one per edition.

  • I already changed once to $stmt1, $stmt2 and etc and it didn’t help, I tbm tried to put only one execution after all if’s and it turned out that only the last column written was edited.

  • The idea is that you edit all the fields at once. Put the form from this screen.

  • But, if I edit all fields at once, when I want to edit only one field (the location for example) the empty fields erase the rest of the content.

  • An issue, in theory, would have all fields filled in before.

  • Yeah, if I take the guy’s id 1 and just edit the name and click on Ubmit, the rest of the data that was supposed to be intact, is gone. If I make the code edit all at once.

  • Edit the question and put the form.

  • 1

    Normally an edit like this, when clicking on the edit link, a search is made for id at the beginning of the page, then for each field, you make a <input type="text" name="nome" value="<?php echo $registro['nome']; ?> " />. I just don’t understand what this picture is ... this is a single screen? or are several and you left in an image only?

  • There are two screens, one before editing and one after editing. .

  • What did you say last would be in the case of an issue printing the values in all fields? I think this way it should work, because with all the values printed in the fields the person edits only what he wants and sends again what was already written. I’ll try to do it that way.

  • some missing due to size but the idea is this: </br><? php $set=' if($localizacao_upd != "") { if $set !=""" { $set = $set +", "} $set=", localization='". $localizacao_upd." '"; } if($mensagem_upd != "") { if $set !=""" { $set = $set +", "} $set = $set +" message='". $mensagem_upd." '"; } if $set !="" { $sql = "UPDATE guestbook SET ". $set." WHERE id='". $id_upd." '"; $stmt = $Conn->prepare($sql); $stmt->execute(); } catch(Pdoexception $e) { echo $sql . " <br>" . $e->getMessage(); } $Conn = null;

  • 1

    It does not work, I tried to change to the PDO INSERT format of that link http://www.mustbebuilt.co.uk/php/insert-update-e-deletande-with-pdo/ and that http://stackoverflow.com/questions/18323065/update-query-with-pdo-and-mysql but it is not working... I think I’ll leave it as it is, creating this new blank line, hopefully it doesn’t weigh in the database..

  • From what I understand, your script updates every satisfied condition, the correct would be to check, and only then update the fields when all conditions are satisfied.

  • I made the complete code, separated the HTML from PHP, put print of the program in operation and still voted as if I had asked the question badly asked. The problem was that you didn’t know how to answer and you didn’t help me at all. 9 months passed and I had to do everything in Webmatrix instead of Mysql.

Show 10 more comments

1 answer

0

Editing usually works this way, by clicking on the link of the listing page the user is redirected to the editar.php, in it is done database search by id, which was passed by $_GET.

Listing.php

$row is listing of all records, has a while/foreach before this link.

<a href="cadastros/editar.php?id=<?php echo $row['id']>EDITAR</a>"

Edit.php

Do the search by id, with the value received in $_GET['id'], then close the php tag, create the html of the form, in each field add the attribute value and open the php tag and write the value of the respective field with $registro['nome_do_campo'].

I recommend creating a new file(gravar.php) to update and update.

How do you know when to include or update the record? If there is a value in the field id_udp it is an update of the opposite is an Insert.

<?php
    include 'conexao.php';

    $id = !empty($_GET['id']) ? $_GET['id'] : 0;

    $sql = "SELECT * FROM guestbook WHERE id = :id"
    $stmt = $db->prepare($sql);
    $stmt->bindValue(':id', $id);
    $stmt->execute();

    $registro = $stmt->fetch(PDO::FETCH_ASSOC);

?>

<form method="post" action="gravar.php">

id: <br><input type="hidden" name="id_upd" value="<?php echo $registro['id'];" />
<br><br>

Nome: <br>
      <input type="text" name="nome_upd" value="<?php echo $registro['nome_upd'];" />
<br><br>

Localização: <br><input type="text" name="localizacao_upd" value="<?php echo $registro['localizacao_upd'];" />  

demais campos ...

</form> 
  • I have one file for each one, one to insert, one to delete and one to display. All are in PDO notation and work perfectly, the only one that doesn’t work is the edit.php file, it only works with notation without PDO (which is the question), but puts a blank line. I’m trying to do it in PDO notation format, but it’s not working, so I opened another question to try to solve here: http://answall.com/questions/93755/update-com-pdo-formul%C3%A1rio-html?

Browser other questions tagged

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