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!
// 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);
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.
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.-
$_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')