Updating records in mysql using array

Discussion in 'PHP' started by cris02, Nov 11, 2010.

  1. #1
    Hello, is there other way instead doing this code? Where fields and value are inside the array.

    $query=mysql_query("UPDATE $tbl SET $fields[0] = $value[0], $fields[1] = $value[1], $fields[2] = $value[2] WHERE id = '".d($_GET['i'])."'");
    PHP:
    Thanks.
     
    cris02, Nov 11, 2010 IP
  2. fr33lanc3

    fr33lanc3 Peon

    Messages:
    38
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You could take this approach...


    // start building qry
    $qry = "update $tbl set ";

    // count how many elements in the array;
    $total = count($fields);

    // loop over total
    for ($i=0; $i<$total; $i++){
    // append to qry so query looks like: field = 'value',
    $qry .= $fields[$i] ." = '".$value[$i]."'," ;
    }

    // chop off last comma
    $qry = substr($qry, 0, -1);
    // add where statement
    $qry .= "WHERE id = '".d($_GET['i'])."'")";

    $result = mysql_query($qry);

    This is not tested, there could be a syntax err in there.
     
    fr33lanc3, Nov 11, 2010 IP
  3. max2010

    max2010 Greenhorn

    Messages:
    81
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    16
    #3
    hm I would execute as many queries as array fields you have, if they are many
    just set the query and execute it inside the loop fetching the array
     
    max2010, Nov 11, 2010 IP