0

我有一个php函数

function insertIntoDb($db, $table) {
    mysql_select_db($db) or die("Could not select database. " . mysql_error());
    $resultInsert = mysql_query("SHOW COLUMNS FROM " . $table);
    $fieldnames=array();
      if (mysql_num_rows($resultInsert) > 0) {
        while ($row = mysql_fetch_array($resultInsert)) {
            $fieldnames[] = $row['Field'];
            $values = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
        }
      }
      $sql = sprintf('INSERT INTO %s (%s) VALUES ("%s")', $table, 
      implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values))); 
      mysql_query($sql); 
      echo '<div class="success">Data was entered into the database successfully!<br><a href="view.php?type=recent">View listing?</a></div>';
}

基本上,我使用表列为用户表单生成字段,然后使用相同的方法插入表中。目前它正在工作,但是如何在将其插入表之前检查输入的值是否为空(例如用户尚未填写字段)?

4

2 回答 2

3

关于检查 null/not-set/empty 值的一些好处:

空同余(===):

$result = $x === NULL

或者

$result = is_null($x)
// $result === TRUE if:
// $x was never set
// was set to NULL

isset

$result = isset($x['some_key'])
// $result === TRUE if $x['some_key'] is either:
// NULL
// does not exist in $x (was never set)

empty

if(empty($x))
// $result === TRUE if $x is either:
// NULL
// FALSE
// (int) 0
// (float) 0.0
// (string) ''
// (string) '0'

上述操作的速度按顺序列出:

  • ===/!==因为他们是运营商
  • isset/empty因为它们是语言结构(不是函数)
  • is_null因为它是一个函数
于 2012-06-30T13:35:18.287 回答
1

替换这个:

while ($row = mysql_fetch_array($resultInsert)) {
    $fieldnames[] = $row['Field'];
    $values = array_intersect_key( $_POST, array_flip($fieldnames) );
}

有了这个:

while ($row = mysql_fetch_array($resultInsert)) $fieldnames[] = $row['Field'];
$values = array_intersect_key( $_POST, array_flip($fieldnames) );
$values = array_filter($values, function($x) { return $x !== ''; });

如果您使用的是 PHP < 5.3,则需要将最后一行替换为:

$values = array_filter($values, create_function('$x', 'return $x !== "";'));
于 2012-06-30T13:46:02.767 回答