如何在进入数据库之前检查值是否为空?

时间:2012-06-30 02:35:14

标签: php mysql insert

我有一个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>';
}

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

2 个答案:

答案 0 :(得分: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因为它是一个函数

答案 1 :(得分: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&lt; 5.3,你需要用这个代替最后一行:

$values = array_filter($values, create_function('$x', 'return $x !== "";'));
相关问题