Correct way to perform a dynamic UPDATE with PHP in Mysql

Asked

Viewed 1,711 times

4

What is the right way to accomplish update dynamic?

the big problem is being dynamic, if I pass only the first parameter and others are not changed.

What is the best way to leave this update only with the parameter I am changing without the need to pass the other sets.

$sqlupdate = " UPDATE eventos ? , ? , ?   WHERE num_codigo_pk = ?";
$sth = $db->prepare($sqlupdate);
$sth->bindValue(1 ,$_POST["nome_evento"], PDO::PARAM_STR);
$sth->bindValue(2 ,$_POST["cod_tipo_evento"], PDO::PARAM_INT);
$sth->bindValue(3 ,$_POST["cod_municipio_evento"], PDO::PARAM_INT);
$sth->bindValue(4 ,$_POST["num_codigo_pk "], PDO::PARAM_INT);
$sth->execute();
  • 2

    You can see here in syntax Highlight that your code does not compile. Missing to close the quotes in the first line. A good IDE will warn you of this... I will publish a reply just for you to see the difference.

  • If you intend to do so, I recommend using ORM to build QUERY.

  • 2

    +1 the question why you are using the PDO library instead of the deprecated mysql functions_*

  • Do you want to know if data has been informed or new name. is equal to old name.? If you tested my answer give feedback on it so I can adjust the answer - edit your question can change the sense of the answers.

  • I have a reply that can help you

  • @Papa Charlie I will test your solution now.

  • @Fábio Lemos Elizandro, put there all help is welcome

  • @Diegosantos the link to my answer is here for you who already use PDO is a smooth transition. If this is a mini tutorial for DBAL Doctrine, it will help you a lot to perform dynamic updates

Show 3 more comments

2 answers

6

You can only enter values and never SQL commands, which includes fields; Example of how you could do your query:

$sqlupdate = " UPDATE eventos SET nome = ? , cod_tipo_evento = ? , cod_municipio_evento = ? WHERE num_codigo_pk = ?";
$sth = $db->prepare($sqlupdate);
$sth->bindValue(1 ,$_POST["nome_evento"], PDO::PARAM_STR);
$sth->bindValue(2 ,$_POST["cod_tipo_evento"], PDO::PARAM_INT);
$sth->bindValue(3 ,$_POST["cod_municipio_evento"], PDO::PARAM_INT);
$sth->bindValue(4 , $_POST["num_codigo_pk "], PDO::PARAM_INT);
$sth->execute();

I also recommend doing some validation on the dandos before inserting them directly; for example:

$codEvento = intval($_POST["cod_tipo_evento"]);
// Ou validar algo para ver se nao esta vazio
$nomEvento = isset($_POST["nome_evento"]) ? $_POST["nome_evento"] : '';

To have all the fields dynamically:

$campos = array();
if (isset($_POST["nome_evento"])) {
  $campos[] = 'nome';
}

if (isset($_POST["cod_tipo_evento"])){
  $campos[] = 'cod_tipo_evento';
}


if (isset($_POST["cod_municipio_evento"])){
  $campos[] = 'cod_municipio_evento';
}

if(count($campos) == 0) {
  die('Nao foi selecionado nenhum campo para atualizar!');
}

$sql = 'UPDATE eventos SET ';
$sql .= implode(" = ?,", $campos);

$sql .= ' = ? WHERE num_codigo_pk = ?';

This way you only generate the UPDATE of the fields that came by the POST;

  • Cool, I understood that bindValue can only be used for values, but the big problem is being dynamic, if I pass only the first parameter and other not changed form, what is the best way to leave this update only with the parameter that I am changing without the need to pass the other set’s.

  • I edited my answer and added a way to leave the dynamic fields. For me this solution is no longer ideal and I suggest you the adoption of an ORM that does much of this work for you.

3

First of all, always ensure data validation. I’ve made a simple example that might suit you to assemble your own mini ORM.

Basically it will combine the received data with the types defined to mount the SQL statement, combining the received data with the typing: nome = str, cod_tipo_evento = int...

QUERY: UPDATE table SET nome = ?, cod_tipo_evento = ?, cod_municipio_evento = ?, num_codigo_pk = ? WHERE num_codigo_pk = ?

The back loop mounts the bindValue with the types of each field and executes.


// data: valores recebidos via form
// type: definindo os tipos
$data = array( 'nome' => 'Papa' , 'cod_tipo_evento' => '1234' , 'cod_municipio_evento' => '4321' , 'num_codigo_pk' => '1' );
$type = array( PDO::PARAM_STR , PDO::PARAM_INT , PDO::PARAM_INT , PDO::PARAM_INT , PDO::PARAM_INT );

foreach( $data as $key => $val )
{
    $cols[] = "$key = ?";
    $vals[] = "$val";
}

// instrução update
$sth = $db->prepare('UPDATE `table` SET ' . implode(', ', $cols) . ' WHERE num_codigo_pk = ?');

// loop nos valores para combinar os tipos
foreach( $vals as $i => $val )
    $sth->bindValue( ($i+1) , $val , $type[$i] );

$sth->execute();

Browser other questions tagged

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