-1

I want to make an update function to update a profile in my DB. Now I have all 20 fields and wants to make a feature where when I can say what data I send it.

Example:

function send_data($a, $b, $c, $d, $e, $id){
    $sql = "UPDATE table SET a=$a, b=$b, c=$c, d=$d, e=$e  WHERE id = $id";
    mysql_query($sql);
}

Now I want to call this function and for example only give A and D

Can this be? if so how?

4 Answers4

4

Consider using an array:

function send_data($data, $id) {
    $build = array();
    foreach($data as $k=>$v) {
        $build[] = "`".$k."` = '".mysql_real_escape_string($v)."'";
    }
    $sql = "UPDATE `table` SET ".implode(", ",$build)." WHERE `id`=".intval($id);
    mysql_query($sql);
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

It is possible in PHP to have default parameters, for example:

function send_data($a, $b = 5, $c = 6, $d = "foo")

Which then can be called by only specifying the arguments without a default value, so this function could be called with 1-4 parameters. The issue then is that you still have to provide arguments in the correct positions, so you can't just specify $a and $d. For example, all the following are valid

send_data(5);                    // Actually send_data(5, 5, 6, "foo");
send_data(5, 3);                 // Actually send_data(5, 3, 6, "foo");
send_data(5, 1, 9);              // Actually send_data(5, 3, 9, "foo");
send_data(5, 1, 9, "bar");       // Actually send_data(5, 3, 9, "bar");

PHP doesn't support keyword arguments either, so another way is to pass in an array, for example:

function send_data($args) {
    do_something_with($args['a']);
}
slugonamission
  • 9,562
  • 1
  • 34
  • 41
0
function send_data( $setData )
  {
    $setVals = array();
    foreach( $setData as $field => $val )
    {
      $value      = mysql_real_escape_string($val);
      $setVals[]  = $field . "='{$value}'";
    }

    $setString = implode(', ', $setVals);

    mysql_query('UPDATE table SET ' . $setString)
  }
0

you can use default parameters in your function by defining the values in the declaration, but as far as i know you cannot "skip" arguments, like when you have the queue $a, $b, $c, you cannot call the function like myfunction(valueforA,, valueforC ). you have to give in every argument from the start until the last one you want to set. like myfunction (valueforA, NULL, ValueforC);

in your case you could use the following:

function send_data($a=NULL, $b=NULL, $c=NULL, $d=NULL, $e=NULL, $id=NULL){
    $sql = "UPDATE table SET a=$a, b=$b, c=$c, d=$d, e=$e  WHERE id = $id";
    mysql_query($sql);

and use it like

send_data(1, 2, NULL, NULL, NULL, 5);

See http://www.php.net/manual/en/functions.arguments.php

Kai
  • 37
  • 5