-1

As the title says, I'm trying to insert a row into a MySQL table using data sent in an HTML form. Some of the form fields can be left blank, however. Previously, for a select statement, I did this loop to check what fields were not empty and form an SQL query string (just for illustration), where $sql is a statment like "SELECT * FROM table WHERE":

for ($i = 0; $i < $size; $i++) {
if( $i != $size - 1 ) {
    if( !empty($formData[$i]) ) {
        $sql = $sql . " {$formFields[$i]} LIKE \"%{$formData[$i]}%\" and"; 
    }
} else {
    if( !empty($formData[$i]) ) {
        $sql = $sql . " {$formFields[$i]} LIKE \"%{$formData[$i]}%\";"; 
    }
    else {
        $sql = substr($sql, 0, strlen($sql)-4 ) . ";"; 
    }
}

}

However in this case now, some of the insert fields can be blank, where previously it didn't matter because I was doing a "SELECT *" and I only had to worry about the WHERE clause. Is there an easier way to do this, other than having a monster of a for loop?

4

4 回答 4

0

您将需要同时构建 2 个字符串,一个用于字段列表,一个用于值列表。

$fields = [];
$values = [];
for ($i = 0; $i < $size; $i++) {
        if( !empty($formData[$i]) ) {
            array_push($fields,$formFields[$i]);
            array_push($values,$formData[$i]);
        }
    }
} 
$sql = "INSERT INTO table(`".implode("`,`",$fields)."`) VALUES('".implode("','",$values)."')";

这当然假设您至少有一个非空白字段并已采取必要的预防措施来防止注入。

于 2013-07-03T20:21:10.987 回答
0

如果您有一个数组,其中键是字段的名称,您可能会使用较小的 for 循环和较少的 if 条件。在 $_POST 上进行数据清理后,您可以执行类似...

    foreach($formFields as $key => $value) {
        if(!empty($formFields)) {
            // build your query
        }
    }

至于不循环遍历所有表单字段,可能没有更快的方法来做到这一点。我想您可以使用像 array_walk 这样的数组函数来遍历您可用的所有字段。不过,您仍然必须遍历数组中的每个元素...

于 2013-07-03T20:13:00.407 回答
0

说真的,当心 Little Bobby Tables:xkcd.com/327/ 像这样构建 sql 字符串是灾难性的。您正在寻找(并使调试更容易)是参数化查询。

从这里开始:如何防止 PHP 中的 SQL 注入?

于 2013-07-03T20:24:37.573 回答
0

我会使用 foreach 循环。这就是它们的用途,它们将使您的代码更容易理解。遍历您可能查询或可能不查询的所有列,如果它们存在于 $_POST/$_GET 中,则添加它们。

这是我编写这样的查询的一般策略:

<?php

$formFields = validate( $_REQUEST ); // PLEASE PLEASE PLEASE VALIDATE/ESCAPE YOUR DATA

// You should also normalize HTML name fields to actual MySQL column names, if they're different

// Columns you may or may not want to query
$columns = array( 'foo', 'bar', 'buzz' );

$where = array();
foreach( $columns as $column )
{
  if( ! empty($formFields[$column]) )
  {
    $where[] = "$column = {$formFields[$column]}";
  }
}

$where = implode( ' AND ', $set );

$sql = "SELECT * FROM t WHERE $where";
于 2013-07-03T20:17:34.020 回答