Help in foreach

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

  1. #1
    Hello,

    I would like to ask some help regarding in this code

    foreach ($_POST as $field => $value){  
      if($value != 'Update'){
          
            //INSERT the value of each field into mysql  using
           //mysql_query(INSERT INTO mytable ( field1, field2, field3)VALUES( $value1, $value2, $value3);
      
      }
    }
    PHP:
    I want to INSERT the value of every fields in mysql database if i click the submit button, any idea? please help. Thanks
     
    cris02, Nov 9, 2010 IP
  2. bartolay13

    bartolay13 Active Member

    Messages:
    735
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    98
    #2
    why not try to build first your query string



    $fields = '';
    $values = '';

    $count = 0;
    foreach ($_POST as $field => $value){
    $comma_delimiter = $count < count($_POST) ? ', ' : '';
    $fields .= $field . $comma_delimiter;
    $values.= $value . $comma_delimiter;
    }

    $sql = 'insert into table ('. $fields .')' values ('. $values .')';


    hows that?
     
    bartolay13, Nov 9, 2010 IP
  3. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #3
    
    
    include('database.php');
    
    $database = new database($yourdatabaseconnection);
    $database->insert('mytable',$_POST);
    
    // To delete a user (primary key detected automatically)
    $database->delete('mytable',$primarykeyValue);
    
    
    PHP:
    Download

    Just make sure that the primary key is part of that $_POST, otherwise it will add it instead of updating it.

    Currently that database class hasn't been released except for the AzizMVC application, I will be releasing it soon standalone. It has other features that you might like.

    This requires PHP 5 & up.
     
    ThePHPMaster, Nov 10, 2010 IP
  4. cris02

    cris02 Member

    Messages:
    55
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    thanks for the reply, i will try that.
     
    cris02, Nov 10, 2010 IP