如何以正确的格式获取此查询?

时间:2017-06-02 19:57:03

标签: php sql mysqli insert

我一直在尝试使用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)

如何用单引号包装数组的值?

任何帮助表示感谢。

4 个答案:

答案 0 :(得分:1)

我发现至少有两个错误。

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

通过在MySQLi中使用预准备语句来修复这两个错误。这不是一个非常复杂的查询,也可能是静态编写的,但是如果你想像这样动态编写它,这不是问题 - 如果你使用的是PHP 5.6,你可以使用数组解包...)。要生成占位符?,我们创建一个数组为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',但如果您记录错误(如您所知),它会生成通知。

答案 1 :(得分:0)

因为你使用了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比它好!

答案 2 :(得分:0)

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

替换

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

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

你甚至附加双引号。

答案 3 :(得分:0)

  

$ columns = implode(&#34;,&#34;,array_keys($ fields));   $ escaped_values = array_map(&#39; mysql_real_escape_string&#39;,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);
}