Update the data in the database without changing the others that already exist - PDO

Asked

Viewed 882 times

4

Hi, I’m trying to create a page to change the registration data with mysql database, but it should only update the data that are filled and not change the other data if it already exists in the database.

I’ve tried a thousand ways and I can’t, they could help me?

Follows the code:

<?php

try{    
//Abre a conexão; 
    include "conexao.php";  

//Pega os dados do formulário; 

    $campos = array();
    $id = $_POST['id'];
    if(!empty($nome)) $campos[]="nome='$nome'";
    if(!empty($apelido)) $campos[]="apelido='$apelido'";
    if(!empty($telefone)) $campos[]="telefone='$telefone'";
    if(!empty($celular)) $campos[]="celular='$celular'";
    if(!empty($email)) $campos[]="email='$email'";
    if(!empty($endereco)) $campos[]="endereco='$endereco'";
    if(!empty($num_end)) $campos[]="num_end='$num_end'";


//Prepara a query; 
    $stmt = $conn -> prepare("UPDATE `clientes` SET ".implode(',', $campos)." WHERE ID = :id");

//Executa a query;
    $stmt->execute([':id' => $id]);
    echo "Dados atualizados com sucesso! :)";   

} 
//Exibe a mensagem caso dê erro;
    catch(PDOException $e) {
    echo $stmt;
    echo 'Error: ' . $e->getMessage();
}

?>
  • If you have solved it, post the solution in the answers section. Changing the question invalidates the existing answers. You can check the history here to copy the solution in the appropriate field: https://answall.com/posts/249405/revisions

  • Thanks, I’m new here and I didn’t know that yet.

4 answers

4

You need to assign the array correctly, now you overwrite the string every if. Also missing to add simple quotes correctly at the time of implode()the ideal was to use Prepared statements and eliminate this problem and sql injections.

In place of:

if(!empty($nome)) $campos = "nome='$nome'";

Do it (don’t forget the other fields):

if(!empty($nome)) $campos[] = "nome='$nome'";

//ou se preferir sprintf()
//$set = sprintf("'%s'",implode("','",  $campos));

$set = "'". implode("','",  $campos) ."'";
$stmt = $conn -> prepare("UPDATE `clientes` SET ". $set ." WHERE ID = $id");

Related:

How to make dynamic bind PDO

  • Adjust and return: Notice: Array to string Conversion in C: xampp htdocs cadastro alterando2.php on line 29 Error: SQLSTATE[42000]: Syntax error or access Violation: 1064 You have an error in your SQL syntax; check the manual that Corresponds to your Mariadb server version for the right syntax to use near ''. implode(',','.Array'). ' WHERE ID = '.6'' at line 1

  • @Rodrigoalves edited the answer.

  • Thanks for the tips, I did a better search, I changed some things but it worked, updated with functional code, hugs! D

4


You have two problems with your code, the first is that with each new field, you are replacing the previous one (as reported by @rray). You should use as an array:

if(!empty($nome)) $campos[] = "nome='$nome'";

However, when it comes to performing the input of your variables in the query, you are doing it wrong.

That:

$stmt = $conn -> prepare("UPDATE `clientes` SET '.implode(',','.$campos').' WHERE ID = '.$id'");

Should be:

$stmt = $conn -> prepare("UPDATE `clientes` SET ".implode(',', $campos)." WHERE ID = '{$id}'");

Basically, where you should close and open string with double quotes, is using single quotes and is added the variable $campos, inside the implode function, as if it were a normal string and not a variable.

More information on:

PHP: Strings

However, this will leave your code vulnerable to SQL Injection. You should use Prepared statements instead:

$stmt = $conn -> prepare("UPDATE `clientes` SET ".implode(',', $campos)." WHERE ID = :id");
$stmt->execute([':id' => $id]);

More information on

PHP: SQL Injection

UPDATE

There is a situation that is not being dealt with in your code. And if no field is changed?

This situation can be easily resolved by checking for items in the array:

if (count($campos) > 0)
{
    /Prepara a query; 
    $stmt = $conn -> prepare("UPDATE `clientes` SET ".implode(',', $campos)." WHERE ID = :id");

    //Executa a query;
    $stmt->execute([':id' => $id]);
    echo "Dados atualizados com sucesso! :)";  
}
else
{
    echo "Nenhum campo foi modificado";  
}

I believe this is the reason for your last mistake.

  • I tried the second way, using the Prepared statements, and returned: Error: SQLSTATE[42000]: Syntax error or access Violation: 1064 You have an error in your SQL syntax; check the manual that Corresponds to your Mariadb server version for the right syntax to use near 'WHERE ID = '6'' at line 1

  • @Rodrigoalves have you tried to execute your query directly in DBMS? Update your code to see how it is and echo the query that is generated by the string.

  • I updated the code as it is currently, sorry but I do not know how to do these two things you asked, echo I tried to do but gave error :(

  • Add before the execute. echo "UPDATE \` SET clients ". implode(',', $fields)." WHERE ID = '{$id}'";` Take the code that is printed and run directly in the database.

  • @Rodrigoalves updated the response with a case that is not being treated.

  • Dude, your information was of paramount importance so that I could find a way to solve the problem, thank you very much, with this I already did a research on the . implode that had never used before, people like you that the community needs. Hugging!

  • I put the code updated and functional with some modifications :D

  • I just wanted to comment on the Entretanto, isso deixará seu código vulnerável a SQL injection. Você deveria utilizar prepared statements no lugar. In fact he continues with the same problem of SQL Injection, since the parameters of SET are not "escaped".

Show 3 more comments

1

I managed to leave the code like this:

    <?php

    try{    

    //Abre a conexão; 
    include "conexao.php";  

    //Pega os dados do formulário; 
    $id = $_POST['id'];

    $campos = array();

    if(!empty($_POST['nome'])){
    $nome = $_POST['nome'];
    $campos[]= "nome='$nome'";
    }

    if(!empty($_POST['apelido'])){
    $apelido = $_POST['apelido'];
    $campos[]="apelido='$apelido'";
    }

    if(!empty($_POST['telefone'])){
    $telefone = $_POST['telefone'];
    $campos[]="telefone='$telefone'";
    }

    if(!empty($_POST['celular'])){
    $celular = $_POST['celular'];
    $campos[]="celular='$celular'";
    }

    if(!empty($_POST['email'])){
    $email = $_POST['email'];
    $campos[]="email='$email'";
    }

    if(!empty($_POST['$endereco'])){
    $endereco = $_POST['endereco'];
    $campos[]="endereco='$endereco'";
    }

    if(!empty($_POST['num_end'])){  
    $num_end = $_POST['num_end'];   
    $campos[]="num_end='$num_end'";
    }


    //Prepara a query; 
    $stmt = $conn -> prepare("UPDATE `clientes` SET ".implode(',', $campos)." WHERE ID = :id");

    //Executa a query;
    $stmt->execute(array(':id' => $id));
    echo "Dados atualizados com sucesso! :)";   

    } 
    //Exibe a mensagem caso dê erro;
    catch(PDOException $e) {
    echo 'Error: ' . $e->getMessage();
    }

    ?>

Thank you all.

-1

Your doubt and something common in the world of API’s, I’ll tell you how else I won’t make the code (this is on you)! Search all the information in the database, and update the information that was passed, the information that was not passed receive the old values (and one way, there are other...).

  • Thanks for the tip buddy, I got around here after 3 days trying haha :D

Browser other questions tagged

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