PHP拆分字符串并在MySQL中插入

时间:2015-06-09 21:08:01

标签: php mysql arrays ajax

我正在使用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

1 个答案:

答案 0 :(得分:0)

这应该可行,但通常不建议使用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
}