Nation
Nation

Reputation: 23

Update by id but only the field i want

Im tryin to make my update form and query to update by id. But when i put the data in the form he updates all the fields even tho it dont have any data so in the database he get gets "0". I need to update just the field that have data.

Can you guys help me?

Its giving me always that i have Undefined variables! And only updates the first and second fields!

Thanks, here´s my code:

    if (isset($_POST['alterar'])) {

    $id_cliente = $_POST["id_cliente"];
    $nome_cliente = $_POST["nome_cliente"];
    $telefone_cliente = $_POST["telefone_cliente"];
    $morada_cliente = $_POST["morada_cliente"];
    $email_cliente = $_POST["email_cliente"];
    $servico = $_POST["servico"];
    $n_pecas = $_POST["n_pecas"];
    $tp_arranjo = $_POST["tp_arranjo"];
    $descricao = $_POST["descricao"];

    } 

    $query = "UPDATE `clientes` SET ";
if ($nome_cliente) $columns[] = "`nome_cliente`        = '{$nome_cliente}'";
if ($telefone_cliente) $columns[] = "`telefone_cliente`= '{$telefone_cliente}'";
if ($morada_cliente) $columns[] = "`morada_cliente`  = '{$morada_cliente}'";
if ($email_cliente) $columns[] = "`email_cliente`   = '{$email_cliente}'";
if ($servico) $columns[] = "`servico`         = '{$servico}'";
if ($n_pecas) $columns[] = "`n_pecas`         = '{$n_pecas}'";
if ($tp_arranjo) $columns[] = "`tp_arranjo`      = '{$tp_arranjo}'";
if ($descricao) $columns[] = "`descricao`       = '{$descricao}'";

$columns = implode(",",$columns);
$query .= $columns . " WHERE id_cliente='$id_cliente'";


    mysql_query($query);

    ?>

Upvotes: 0

Views: 112

Answers (1)

CrayonViolent
CrayonViolent

Reputation: 32537

You need to change your query to only list columns to be updated if you have values to update them with. This requires building the query string dynamically based on conditions.

Example:

$query = "update `clientes` set ";
if ($nome_cliente) $columns[] = "`nome_cliente`= '{$nome_cliente}'";
if ($telefone_cliente) $columns[] = "`telefone_cliente`= '{$telefone_cliente}'";
//etc..

$columns = implode(",",$columns);
$query .= $columns . " where id_cliente='$id_cliente'";

NOTE: As others have mentioned, this is not secure! You should always sanitize user input before passing it to your database.

Upvotes: 1

Related Questions