5

Considering I'm building a form and posting the data to PHP, a typical insert query for me goes like this:

$sql = "INSERT INTO news
            (title, body) 
            VALUES (?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST["title"], $_POST["body"]));
$stmt->closeCursor();

This looks fine for a small query, and it is my understanding that this keeps me safe from the likes of SQL injection and whatnot.

But what if I need to work with a pretty big form? Something like...

$sql = "INSERT INTO ficha_item
    (titulo, tipo_produto, quantidade_peso, unidade_de_venda, 
    unidades_por_caixa, caixas_piso, pisos_palete, tipo_de_palete, 
    unidades_palete, caixas_palete, uni_diametro, uni_largura, 
    uni_profundidade, uni_altura, uni_peso_bruto_unidade, caixa_largura, 
    caixa_profundidade, caixa_altura, altura_palete, volume_unidade, 
    peso_caixa, peso_palete) 
    VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

I think it becomes tedious counting all these question marks. Is there a cleaner way to do this with PDO?

1
  • Consider an ORM instead of building such monstrosities manually.
    – DCoder
    Dec 31, 2012 at 12:22

3 Answers 3

6

I would do something like this:

$fields = array(
    'titulo', 
    'tipo_produto', 
    'quantidade_peso', 
    'unidade_de_venda', 
    'unidades_por_caixa', 
    'caixas_piso', 
    'pisos_palete', 
    'tipo_de_palete', 
    'unidades_palete', 
    'caixas_palete', 
    'uni_diametro', 
    'uni_largura', 
    'uni_profundidade', 
    'uni_altura', 
    'uni_peso_bruto_unidade', 
    'caixa_largura', 
    'caixa_profundidade', 
    'caixa_altura', 
    'altura_palete', 
    'volume_unidade', 
    'peso_caixa', 
    'peso_palete'
);
$sql = 'INSERT INTO ficha_item ( %s ) VALUES ( %s )';
// make a list of field names: titulo, tipo_produto /*, etc. */
$fieldsClause = implode( ', ', $fields );
// make a list of named parameters: :titulo, :tipo_produto /*, etc. */
$valuesClause = implode( ', ', array_map( function( $value ) { return ':' . $value; }, $fields ) );
// or, with create_function
$valuesClause = implode( ', ', array_map( create_function( '$value', 'return ":" . $value;' ), $fields ) );
$sql = sprintf( $sql, $fieldsClause, $valuesClause );

// $sql is now something similar to (formatted for display):
// INSERT INTO ficha_item
//     ( titulo, tipo_produto /*, etc. */ )
// VALUES
//     ( :titulo, :tipo_produto /*, etc. */ )

$stmt = $db->prepare($sql);

// if the keys in $_POST match with $fields, you can now simply pass $_POST here
$stmt->execute( $_POST );
// or, as per Bill Karwin's sound suggestion, with the intersection of $_POST
$stmt->execute( array_intersect_key( $_POST, array_flip( $fields ) ) )

In other words, use named parameters, and have them be dynamically generated based on the $fields array. Although named parameters are not strictly necessary; they do help make things easier, because the order of elements passed to, for instance, PDOStatement::execute()doesn't matter now anymore.

This assumes though, that the number of elements and their keys in $_POST, exactly match the number of fields and their names in $sql.

5
  • 3
    +1 but I would recommend restricting the parameter values: $stmt->execute(array_intersect_key($_POST, array_flip($fields))). Dec 31, 2012 at 7:52
  • Combined with Bill's input, this looks good. My test server is not running PHP 5.3 though, could I get an example using create_function? (PHP versions below 5.3 don't support anonymous functions), I tried implementing this on my own, but my PHP newbie-ness is impairing me! Dec 31, 2012 at 10:34
  • @BillKarwin Thanks Bill, I've added your suggestion. Dec 31, 2012 at 12:20
  • 1
    @JoaoFerreira Done. You should be good now. The key with create_function is to use single quotes around their arguments, otherwise variable names get parsed. Perhaps this was why you couldn't get it to work (just a wild guess though). Dec 31, 2012 at 12:24
  • Fantastic answer. Made a generic function version of this for my own use that's very handy. Sep 3, 2013 at 5:32
2

You may create your SQL dynamically:

$allowed_fields = array(
    'titulo', 
    'tipo_produto', 
    'quantidade_peso', 
    'unidade_de_venda', 
    'unidades_por_caixa', 
    'caixas_piso', 
    'pisos_palete', 
    'tipo_de_palete', 
    'unidades_palete', 
    'caixas_palete', 
    'uni_diametro', 
    'uni_largura', 
    'uni_profundidade', 
    'uni_altura', 
    'uni_peso_bruto_unidade', 
    'caixa_largura', 
    'caixa_profundidade', 
    'caixa_altura', 
    'altura_palete', 
    'volume_unidade', 
    'peso_caixa', 
    'peso_palete'
);

$columns = "";
$values = "";
$values_arr = array();
foreach ( $_POST as $key=>$value )
{
    if ( !in_array($key, $allowed_fields) ) continue;
    $columns .= "$key, ";
    $values .= "?, ";
    $values_arr[] = $value;
}
// now remove trailing ", " from $columns and $values
$columns = rtrim($columns, ", ");
$values = rtrim($values, ", ");
// finish them
$sql = "INSERT INTO ficha_item($columns) VALUES($values)";
$stmt = $db->prepare($sql);
$stmt->execute($values_arr);
$stmt->closeCursor();
1

Using bindParam method, it's the clea(n|r)est way to do what you expect. This is more understandable than with question marks. So the code will be more maintainable.

Example from the official php doc :

Example #1 Execute a prepared statement with named placeholders

<?php
/* Execute a prepared statement by         binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.