【问题标题】:How can I get this query in correct format?如何以正确的格式获取此查询?
【发布时间】:2017-06-02 19:57:02
【问题描述】:

我一直在尝试使用 php 将一些数据输入到我的 sqli 数据库中。

当我在 PHPMyAdmin 上通过 GUI 执行插入查询时,变量需要用单引号括起来..

到目前为止,这就是我构建查询的方式:

$fields = array('`appName`' => $_POST[appName],
                    '`appDescription`' => $_POST[appDescription],
                    '`UploadDate`' => date("Y-m-d"),
                    '`appWebsite`' => $_POST[appWebsite]);
printarray($fields);

print "<br>";
print "<br>";

$columns = implode(", ",array_keys($fields));
$escaped_values = array_map('mysql_real_escape_string', array_values($fields));
$values  = implode(", ", $escaped_values);

$sql = "INSERT INTO `applist`.`apps` ($columns) VALUES ($values)";

print $sql;
print "<br>";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error";
}

这给了我这样的查询..

INSERT INTO `applist`.`apps` (`appName`, `appDescription`, `UploadDate`, `appWebsite`) 
VALUES (SDD, DDD, 2017-06-02, DDDD)

如何获取用单引号括起来的数组的值?

任何帮助表示赞赏。

【问题讨论】:

  • 不要使用字符串连接构建查询。使用mysqliPDO 带有绑定参数的预处理语句,如this post 中所述。
  • 在这里混合 API,这是行不通的。您的查询并不需要动态构建它的大或复杂。当然,您可以,但至少使用准备好的语句来构建它。

标签: php sql mysqli insert


【解决方案1】:

我至少可以发现两个错误。

  • 查询中的字符串周围缺少单引号
  • 混合 API(mysql_mysqli_ 不混合),您使用 mysql_real_escape_string()

通过在 MySQLi 中使用准备好的语句修复了这两个错误。这不是一个很复杂的查询,还不如静态写,但如果你想像这样动态写,这不是问题——如果你使用的是 PHP 5.6,你可以使用 array unpacking em> (...)。为了生成占位符?,我们创建了一个包含count($fields) 个元素的数组,所有元素都以? 作为值。这是通过array_fill() 完成的。然后我们 implode() 将其放置到位,就像我们对列所做的那样。

$fields = array('`appName`' => $_POST['appName'],
                '`appDescription`' => $_POST['appDescription'],
                '`UploadDate`' => date("Y-m-d"),
                '`appWebsite`' => $_POST['appWebsite']);
$columns = implode(", ",array_keys($fields));

$sql = "INSERT INTO `applist`.`apps` ($columns) VALUES (".implode(", ", array_fill(0, count($fields), '?')).")";

if ($stmt = $conn->prepare($sql)) {
    $stmt->bind_param(str_repeat("s", count($fields)), ...$fields);
    if ($stmt->execute())
        echo "New record created successfully";
    else 
        echo "Insert failed";
    $stmt->close();
} else {
    echo "Error";
}

这会处理引用字符串并防止 SQL 注入。

要获取您可能遇到的任何错误,请使用mysqli_error($conn) 和/或mysqli_stmt_error($stmt)。这将告诉你究竟出了什么问题。

您还应该引用 POST 数组中的索引。 PHP 会解决这个问题,并将appName 转换为'appName',但如果您记录错误(应该如此),它会生成通知。

【讨论】:

    【解决方案2】:

    因为你使用的是 implode,所以你可以用它加上引号,并在 sql 查询中添加开始和结束引号:

    $fields = array('`appName`' => $_POST[appName],
                        '`appDescription`' => $_POST[appDescription],
                        '`UploadDate`' => date("Y-m-d"),
                        '`appWebsite`' => $_POST[appWebsite]);
    printarray($fields);
    
    print "<br>";
    print "<br>";
    
    $columns = implode(", ",array_keys($fields));
    $escaped_values = array_map('mysql_real_escape_string', array_values($fields));
    $values  = implode("', '", $escaped_values); //add qoutes
    
    $sql = "INSERT INTO `applist`.`apps` ($columns) VALUES ('$values')"; //add start and end qoutes
    
    print $sql;
    print "<br>";
    
    if (mysqli_query($conn, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error";
    }
    

    但这不是很好的解决方案,可能其他查询出现错误!用PDO比它好!

    【讨论】:

      【解决方案3】:

      您需要将单引号附加到每个数组值。

      替换

      $values  = implode(", ", $escaped_values);
      

      $values = "'" . implode ( "', '", $escaped_values ) . "'"; 
      

      你甚至可以附加双引号。

      【讨论】:

        【解决方案4】:

        $columns = implode(", ",array_keys($fields)); $escaped_values = array_map('mysql_real_escape_string', array_values($fields));

        哎哟。不好。

        Kudos 试图转义内容,但如果数据包含逗号,您将无法使用此代码。

        您已经开始使用一种很好的通用方法来插入数据,考虑一下:

        function insert($db_conn, $table, $data)
        {
           $ins_vals=array(); // note we write the transformed data to a new array
              // as we may be modifying the column names too
           foreach ($data as $key=>$val) {
               // we need to protect the column names from injection attacks as
               // well as the data hence:
               $quoted_key="`" . str_replace("`", "", $key) . "`";
        
               // next we create an appropriate representation of the data value
               if (is_null($val)) {
                   $ins_vals[$quoted_key]="NULL"; // in SQL 'NULL' != NULL
               } else if (is_numeric($val)) {
                   // nothing to change here
                   $ins_vals[$quoted_key]=$val;   // no need to quote/escape
               } else {
                   $ins_vals[$quoted_key]="'" 
                       . mysqli_real_escape_string($dbconn, $val) 
                       . "'";
               }
           }
           // then we stick the bits together in an SQL statement
           $cols=implode(",", array_keys($ins_vals));
           $vals=implode(",", $ins_vals);
           $sql="INSERT INTO $table ($cols) VALUES ($vals)";
           return mysqli_query($dbconn, $sql);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-04
          • 1970-01-01
          • 1970-01-01
          • 2015-06-23
          • 2010-09-07
          • 2021-07-26
          • 2013-08-07
          相关资源
          最近更新 更多