this is my code:
<input type="text" name="text[]" />
<input type="text" name="text[]" />
<input type="text" name="text[]" />
if (!empty($_POST['text'])) {
foreach ($_POST['text'] AS $value) {
// add to the database
$sql = 'INSERT INTO tableName SET fieldName 开发者_开发技巧= "' . mysql_real_escape_string($value) . '"';
}
}
I want this to only insert the fields that are filled, for example if the first two inputs are filled, insert those and skip the last one which is empty.
You're already using empty()
to check $_POST
you can also use it to check $value
if (!empty($_POST['text'])) {
foreach ($_POST['text'] AS $value) {
// add to the database
if (!empty($value))
$sql = 'INSERT INTO tableName SET fieldName = "' . mysql_real_escape_string($value) . '"';
}
The most brain-dead way to solve the problem would be to check the string length of each element in the text array.
foreach( $_POST['text'] as $value ) {
if( !empty( $value ){
// add to the database
$sql = 'INSERT INTO tableName SET fieldName = "' . mysql_real_escape_string($value) . '"';
}
}
However, I would seriously consider switching to a framework that does some sort of form validation. I hear good things about cakePHP and CodeIgniter, and they may be worth checking out.
精彩评论