1

I am making a form that builds itself from a given db and table. However I have come across a snag when it comes to the Insert function. I already made it so that all the fields generate input, textareas what have you on a page with the correct name. Now all I need to do is insert it into the db on post. But I need to recreate the array in format (this,that,this) using implode and I'm not sure how to do this.

 $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table);
$fieldnames=array();

if (mysql_num_rows($resultInsert) > 0) {
        while ($row = mysql_fetch_array($resultInsert)) {
            echo $fieldnames[] = $row['Field']; #currently outputting titlebodytextcreated (three fields i have)
        }
      }


// FORMAT: field_name = $_POST[fieldname]

$values = array('title'=>$_POST['title'],'bodytext'=>$_POST['bodytext']); # need this to be autogenerated by the field names

echo "<br>" . sprintf('INSERT INTO %s (%s) VALUES ("%s")', 'testdb', 
implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values))); 

// add loop for id to be generated in a hidden field, along with all other excluded fields so that the
// update will process correctly in the insert into phase
1
  • this is really bothering me haha. im kindof a noobie to php. but i really want to get this code to work Commented Jun 26, 2012 at 13:49

1 Answer 1

1

Would this work?

$values = array_intersect_key( $_POST, array_flip($fieldnames) );

or, rather, if you want to ensure that all values in $fieldnames have a key in $values even when the corresponding key in $_POST is empty:

$values  = array_flip($fieldnames);  
$values += array_intersect_key( $_POST, $values );
Sign up to request clarification or add additional context in comments.

2 Comments

seems to be working! thanks! im going to run some more tests but i think u nailed it
how would one apply this method to an update field? stackoverflow.com/questions/11277580/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.