How to keep the variable with the same value in the database?

3

I have a question in the code below:

<?php
include "conexao.php";  

$id = $_POST["id"];
$nome = isset((trim(ucwords($_POST["nome"])))) : (trim(ucwords($_POST["nome"]))) : 
$apelido = trim(ucwords($_POST["apelido"]));
$telefone = trim($_POST ["telefone"]);
$celular = trim($_POST ["celular"]);
$email = strtolower($_POST ["email"]);
$endereco = $_POST ["endereco"];
$num_end = $_POST ["num_end"]; 

//Query para atualizar os dados no banco; 
$sql = "UPDATE 'clientes' SET nome = '$nome', apelido = '$apelido', telefone = '$telefone', celular = '$celular', email = '$email', endereco = '$endereco', num_end = '$num_end' WHERE ID = '$id'"; 

//Executa a query;
$query = $conecta->query($sql);

//Fecha a conexão; 
$conecta->close(); 
echo "Dados atualizados com sucesso! :)";                   
?>

How do I keep the value in the database if I leave the "name" field blank, for example?

Because if I let:

$nome = isset((trim(ucwords($_POST["nome"])))) : (trim(ucwords($_POST["nome"]))) : ""; 

It will change the database name and leave it blank, but I want the value that was already there saved in the database to hold.

Is it too complicated? Sorry for the silly question, but I looked in different forums something similar but did not find.

    
asked by anonymous 20.09.2017 / 00:29

2 answers

4

This should resolve:

if($nome == ''){
   $nome = null;
} 

$sql = "UPDATE 'clientes' SET nome = coalesce('$nome', nome), apelido = '$apelido', telefone = '$telefone', celular = '$celular', email = '$email', endereco = '$endereco', num_end = '$num_end' WHERE ID = '$id'"; 

The comparison operator coalesce returns the first value not null that was passed to it.

    
20.09.2017 / 00:41
2

One of the ways is to conditionally generate query :

// cria um array vazio.
$campos = array(); 

// se houver algum valor em $nome, adiciona "nome='$nome'" em $campos
if(!empty($nome))    $campos[] = " nome    = '$nome'";
// repete a lógica para todos opcionais:
if(!empty($apelido)) $campos[] = " apelido = '$apelido'";
...

and so on.

Next:

if(count($campos)) { // se algum campo for preenchido
   $sql = 'UPDATE 'clientes' SET '.implode(',',$campos).' WHERE ID = $id'; 
   ... executa a query ...
}


Important!

Regardless of the chosen solution, it is crucial to learn to avoid SQL injections, for the sake of security:

  

How SQL Injection Happens?

  

What is PHP Injection? What's the difference between it and SQL Injection? And how to avoid it?

  

How to prevent SQL injection in my PHP code (it's not mysqli, but the logic is the same )

    
20.09.2017 / 01:41