Thatguy
Thatguy

Reputation: 33

PHP Dynamic fields INSERT MySQL

I have a dynamic form that has lets say the following fields:

 <input type="text" name="firstname">
 <input type="text" name="surname">
 <textarea name="description">

Lets say I have a table on Mysql that has the same column names.

When I post I want the array to split into column names and values and then insert it into a prepared statement:

I've tried the following:

foreach($_POST as $key => $value) {
$keys .= $key.',';
$values .= $value.',';
$q.= '?,';
$type .= 's';

}
rtrim($keys,',');
rtrim($values,',');
rtrim($q,',');

 $insert_stmt = $mysqli->prepare("INSERT INTO ".$form_table." (".$keys.") VALUES (".$q.")");
 $insert_stmt->bind_param($type, $values);  
 $insert_stmt->execute();

It seems to fail on bind_param() failed

I'm guessing it's seeing $values as one long string..am I getting close?

Upvotes: 0

Views: 94

Answers (1)

P S
P S

Reputation: 11

//i - integer
//d - double
//s - string
//b - BLOB

$type = '';
$keys = '';
$values = '';
foreach($_POST as $key => $value) {
    $keys .= $key.',';
    $values .= $value.',';

    //change type according to your need or based on your data type.
    $type .= 's';
}
rtrim($keys,',');
rtrim($values,',');


//use keys, type and values

Upvotes: 1

Related Questions