|
Posted by Umberto Salsi on 05/04/07 07:52
john <puopolo@gmail.com> wrote:
> However, pulling out each variable from the $_POST array seems
> awkward.
Here are some ideas:
1. Naive solution:
function string_field($s){ return "'".my_db_escape_str($s)."'"; }
function int_field($i){ checks_proper_int($i); return $i; }
$sql = "INSERT INTO myTable (f1, f2, f3) VALUES ("
. string_field( $_POST['f1'] )
. int_field( $_POST['f2'] )
. string_field( $_POST['f3'] ) .")";
my_db_query($sql);
2. Improving the point 1 adding the validation. A global string $err is
set with the errors we found:
$err = "";
function string_field($name, $maxlen)
{
$value = trim( $_POST[$name] );
$GLOBALS['err'] .= checks_proper_char_encoding($value);
if( mb_strlen($value) > $maxlen )
$GLOBALS['err'] .= "Field $name too long, max $maxlen chars allowed. ";
return "'".my_db_escape_str($s)."'";
}
function int_field($name, $sign_allowed, $maxdigitsintpart, $maxdigitsfracpart)
{ ... }
$sql = "INSERT INTO myTable (f1, f2, f3) VALUES ("
. string_field( 'f1', 20 )
. int_field( 'f2', 9, 2 )
. string_field( 'f3', 20 ) .")";
if( strlen($err) == 0 ){
my_db_query($sql);
} else {
echo "ERROR: $err";
}
3. Using a sort of "SQL-printf" function. If you know how the printf()
function works, this should look familiar:
function field($fmt, $name)
{ ... }
$sql = "INSERT INTO myTable (f1, f2, f3) VALUES ("
. field( "20s", 'f1' )
. field( "9.2f", 'f2' )
. field( "10s", 'f3' ) .")";
if( strlen($err) == 0 )...
4. Using the interesting feature of the PHP know as "functions with variable
number of arguments". In this case the arguments are the name of the table
and a "field descriptor" for each field containing the type descriptor (as
above) and the field name. A global variable $err is set with the errors
found validating every field. The function returns the complete SQL query
ready to be submitted to the DB:
function build_sql_insert( $table /*, field descriptors here */)
{...}
$sql = build_sql_insert("myTable", "20s f1", "9.2i f2", "10s f3");
if( strlen($err) == 0 )...
Similar functions performs SELECT and UPDATE, but some more arguments can
be required for the WHERE part of the SQL request.
Regards,
___
/_|_\ Umberto Salsi
\/_\/ www.icosaedro.it
Navigation:
[Reply to this message]
|