Reputation: 4491
I currently have a form with over 50+ fields, with roughly 20 optional fields.
Is there any easy way to process $_POST
data in one hit to remove empty strings and change them to NULL prior to inserting into the database, or do they have to be done one by one in the following method:
if ($_POST['field_x'] == "") {
$_POST['field_x'] = NULL;
}
Upvotes: 3
Views: 9682
Reputation: 2359
You can do something like this:
foreach ($_POST as $k => $v) {
if(empty($v) || $v === '') {
$_POST[$k] = null;
}
}
echo '<pre>';var_dump($_POST);echo '</pre>';
Upvotes: 0
Reputation: 645
based on the answer of hakre my solution for this is:
foreach ($_POST as &$v) {
$v = (is_numeric($v) ? $v : ($v === "" ? "NULL" : "'" . $v . "'"));
}
unset($v);
So afterwards I concat my SQL command like this:
$sql = "INSERT INTO $mytable (number, name, description)
VALUES (" . $_POST['number'] . ","
. $_POST['name'] . ","
. $_POST['description'] . ")";
In fact I got no other method working to really get NULL for all emtpy $_POST variables into the database field.
Upvotes: 0
Reputation: 1
Assign $_POST['data'] to a variable, like $a=$_POST['data']; after usage of variable $a, make it empty like $a=""; or $a=null;
Upvotes: -1
Reputation: 1
(isset($_POST['x']) ? $_POST['x'] : NULL)
Easier inline method for PDO binding. isset() is a special function. You can't call another function to then check isset() on a variable.
Example:
$conn = new PDO($pdo_connection, $pdo_username, $pdo_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM `t` WHERE `x`=:x');
$stmt->bindValue(':x', (isset($_POST['x']) ? $_POST['x'] : NULL), PDO::PARAM_STR);
$stmt->execute();
Upvotes: 0
Reputation: 197787
Setting all elements that are an empty string to NULL:
foreach ($_POST as &$v) {
if ($v !== "") {
continue
}
$v = NULL;
}
unset($v); // remove the reference (alias) to the last element of $_POST
Upvotes: 4
Reputation: 3034
You can use array_filter:
$post = array_filter($_POST);
http://php.net/manual/en/function.array-filter.php
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
To only remove empty strings you can use:
function drop_empty($var)
{
return ($var === '') ? NULL : $var;
}
$post = array_filter($_POST, 'drop_empty');
If you don't want to drop values, but only want to set them to NULL: use array_map
:
$post = array_map('drop_empty', $_POST);
Upvotes: 10
Reputation: 141827
This is nice and concise, but it will also remove POST values like the integer 0
or anything else that evaluates to false when cast to (bool)
$_POST = array_filter($_POST);
If that won't work for you you can use a callback function that compares using ===
to ""
You should also note that this is more like calling unset()
rather than setting the array element to NULL
, which is quite similar and probably good enough / even better for your situation.
Upvotes: 3