【问题标题】:PHP split a string and insert in MySQLPHP拆分字符串并插入MySQL
【发布时间】:2015-08-24 21:49:33
【问题描述】:

我正在使用 AJAX 将一组值发送到 PHP 页面,该页面会将数据插入 MySQL 数据库。问题是我不确定如何将数据拆分为 5 个不同的变量并循环插入数据库。

AJAX 请求: 数组:

[".testimonial", 1119, 316, 1663, 608, "#header", 723, 66, 1663, 608]

发布数组:

使用“;”发送数组参数进行拆分。

clicks  
.testimonial;1119;316;1663;608;#header;723;66;1663;608

发送源:

clicks=.testimonial%3B1119%3B316%3B1663%3B608%3B%23header%3B723%3B66%3B1663%3B608

PHP 页面

<?php

$clicks = $_GET["clicks"];
$clickArray = explode(";",$clicks);
$arrays = array_chunk($clickArray, 5);

foreach ($arrays as $array_num => $array) {
  foreach ($array as $item_num => $item) {
    echo "". $item . "<br/>";
  }
}


$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "clickmap";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


$sql = "INSERT INTO data (user_id, identifier_name, pos_x, pos_y, window_width, window_height, status)
VALUES ('1', '$postIdentifier', '$postPos_x', '$postPos_y','$postWindowWidth','$postWindowHeight', 'ok')";


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>

当前 PHP 结果:

.testimonial
1119
316
1663
608
#header
723
66
1663
608
New record created successfully

【问题讨论】:

  • 什么?为什么不直接发送 JSON?并使用 JSON 数组中的键名,使 PHP 端更容易。
  • 您在查询中使用的任何变量都没有得到定义。所以你要插入空字符串。然后无论如何都不会在查询中使用任何 json/array 操作的东西,所以这都是无用/无意义的代码。
  • @AbraCadaver 我现在将尝试使用 JSON。出于某种原因,我认为它不会起作用。 Marc B 问题是如何在拆分字符串并进行循环时定义它们。您的评论比代码更无用/毫无意义。
  • 警告:使用mysqli 时,您应该使用参数化查询和bind_param 将用户数据添加到您的查询中。 请勿使用字符串插值来完成此操作,因为您将创建严重的SQL injection bugs从不$_POST数据直接放入查询中。

标签: php mysql arrays ajax


【解决方案1】:

这应该可行,但通常不建议使用extract,因为它很容易导致难以调试的错误。

$keys = array('postIdentifier', 'postPos_x', 'postPos_y','postWindowWidth','postWindowHeight');

foreach ($arrays as $array_num => $array) {
  $values = array();
  foreach ($array as $item_num => $item) {
    $values[] = $item;
  }
  $data = array_combine($keys, $values);
  extract($data); // now your variables are declared with the right values http://php.net/manual/en/function.extract.php

  // .. run SQL insert here
}

【讨论】: