-1

I am sure there is a much better way to do this, I am just unaware of how to do it. Basically I am submitting a form to a page that will grab the info and stuff it into a MYSQL database. Currently I have it set up so I declare the variable and set its value from the _POST, and then later add it to the correct MYSQL column. Here is a snippet:

$k1 = $_POST['k1'];
$k2 = $_POST['k2'];
$k3 = $_POST['k3'];
...

$sql = "INSERT INTO patches (k1, k2, k3, ...) VALUES ('$k1', '$k2', 'k3', ... )";

Obviously this is a hassle with a large amount of fields. What steps could I take to improve this? Thanks!

2
  • you can make a string by for loop and then insert to mysql string Commented Jan 1, 2014 at 9:02
  • 2
    Why do this in the first place? Just leave the data in an array. Commented Jan 1, 2014 at 9:03

4 Answers 4

2

Assuming that every single post field is a table column, you can do something like this.

$keys = implode(',', array_keys($_POST));

$values = implode(',', array_map(function($value) {
    return "'". addslashes($value) ."'";
}, array_values($_POST)));

$sql = "INSERT INTO patches ($keys) VALUES ($values)";

Unfortunately, this is method would be very vulnerable to SQL injection. A better method is a similar approach, but preparing a statement and binding the values using PDO.

$keys = implode(',', array_keys($_POST));
$params = implode(',', array_fill(0, count($_POST), '?'));

$sql = $dbHandle->prepare("INSERT INTO patches ($keys) VALUES ($params)");

$sql->execute(array_values($_POST));

Where $dbHandle is a PDO connection resource. You can find more information about PDO here.

Sign up to request clarification or add additional context in comments.

Comments

2

Using [] in the input element's name attribute like so:

<input name="k[]" type="text">
<input name="k[]" type="text">
<input name="k[]" type="text">

will return an array on the PHP end:

$k = $_POST['k'];

and you can use implode() to format those values for SQL:

$sql = "INSERT INTO patches (k1, k2, k3, ...) VALUES ('".implode("','", $k)."');";

-source code by User Pekka, found here.-

2 Comments

The problem with this is that the values have no associativity. This is assuming that the order the values were sent in the post header are respective to the order of columns in each row.
@AustinBrunkhorst A fair point. I would argue that associativity is indeed established in the insert statement, though without modularity.
1
// you should not work with the $_POST array itself, but rather extract values from it
$foo = array('k1' => 1, 'k2' => 2, 'k3' => 3);
$keys = array_keys($foo);
$sql  = 'INSERT INTO patches';
$sql .= '(' . implode(',', $keys) . ')';
array_walk($keys, function(&$val){
    $val = ":$val";
});
$sql .= 'VALUES (' . $keys . ')';

And then you can call your query as such:

$query = $pdo->prepare($foo);
$query->execute($foo);

Comments

0
$_POST["k1"] = "1";
$_POST["k2"] = "2";
$_POST["k3"] = "3";
$_POST["k4"] = "4";
$_POST["k5"] = "5";
$_POST["k6"] = "6";

$str_keys = "";
$str_val = "";
foreach ($_POST as $key => $val) {
        $str_keys .= ($str_keys) ? ",".$key : $key;

        $str_val .= ($str_val) ? ",'".$val."'" : "'".$val."'";
}
$sql = "INSERT INTO patches (".$str_keys.") 
        VALUES (".$str_val.")";

echo $sql ;

Formed query

INSERT INTO patches (k1,k2,k3,k4,k5,k6) VALUES ('1','2','3','4','5','6')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.