如何内爆$ _SESSION ARRAY然后插入到Mysql中

时间:2017-08-24 22:42:48

标签: php mysql arrays session

我首先从TEST数据库中检索数据

$Sql = "SELECT * FROM test";
$result = array();
$res = mysqli_query($conn, $Sql);

while($row = mysqli_fetch_array($res, MYSQL_NUM)){
$result[] = $row;
}

在会话中存储数据

$_SESSION['Sql'] = $result;

从SESSION或结果打印完美

echo '<pre>';
print_r($_SESSION['Sql']);
echo '</pre>';

echo '<pre>';
print_r($result);
echo '</pre>';

结果 - 数据库中只有2条记录,包含3列

Array
(
[0] => Array
    (
        [0] => 1
        [1] => Kent Mercer
        [2] => 53
    )

[1] => Array
    (
        [0] => 2
        [1] => Linda Carter
        [2] => 63
    )

)

然后我尝试插入TEST2数据库

  $fields = implode(",", array_keys($_SESSION['Sql']));
  $newdata = implode(",", $_SESSION['Sql']);

  $query = ("INSERT INTO test2 ($fields)
  VALUES ('$newdata')");

  if (mysqli_query($conn, $query)) {

  echo "New record created successfully";
  } 

  else{

  echo "Error: " . $query . "<br>" . mysqli_error($conn);

  }

我收到以下错误

 Error: INSERT INTO test2 (0,1) VALUES ('Array,Array')
 You have an error in your SQL syntax; check the manual that corresponds
 to your MySQL server version for the right syntax to use near '0,1) 
 VALUES ('Array,Array')' at line 1 

1 个答案:

答案 0 :(得分:0)

您可能已关闭通知。

你有一个多维数组,因此你必须先进行更深入的访问才能崩溃。

请参阅your trouble

$_SESSION['Sql']=[[1,'Kent Mercer',53],[2,'Linda Carter',63]];
var_export(implode(',',$_SESSION['Sql']));

输出:

<br />
<b>Notice</b>:  Array to string conversion in <b>[...][...]</b> on line <b>5</b><br />
<br />
<b>Notice</b>:  Array to string conversion in <b>[...][...]</b> on line <b>5</b><br />
'Array,Array'

如何为INSERT查询准备数据:

代码:(Demo

$_SESSION['Sql']=[[1,'Kent Mercer',53],[2,'Linda Carter',63]];

$str = implode(',', array_map(function($a){return "({$a[0]},'{$a[1]}',{$a[2]})";},$_SESSION['Sql']));
// wrap each row of data in its own set of parentheses
// this assumes that `id` and `age` are expecting numbers, and `name` is expecting a string.

echo "These are the parenthetical values:\n";
echo $str;
echo "\n\nQuery: INSERT INTO `test2` (`id`,`name`,`age`) VALUES $str";
// for best practice, wrap your tablename and columns in backticks.
// NAME is a mysql keyword

输出:

These are the parenthetical values:
(1,'Kent Mercer',53),(2,'Linda Carter',63)

Query: INSERT INTO `test2` (`id`,`name`,`age`) VALUES (1,'Kent Mercer',53),(2,'Linda Carter',63)

出于安全原因,您学习的下一步是mysqli prepared statements with placeholders

这是一个片段,内置错误检查语句准备,绑定和执行,以便您可以隔离任何问题。 (我没有在发布之前对此进行测试,如果有任何问题请发表评论。我不希望任何人复制拼写错误或有缺陷的代码。)

代码:

$_SESSION['Sql']=[[1,'Kent Mercer',53],[2,'Linda Carter',63]];
if(!($stmt=$mysqli->prepare('INSERT INTO `test2` (`id`,`name`,`age`) VALUES (?,?,?)'))){  // use ?s as placeholders to declare where the values will be inserted into the query
    echo "<p>Prepare failed: ",$mysqli->error,"</p>";  // comment this out or remove error details when finished testing
}elseif(!$stmt->bind_param("isi",$id,$name,$age)){  // assign the value types and variable names to be used when looping
    echo "<p>Binding failed: (",$stmt->errno,") ",$stmt->error,"</p>";  // comment this out or remove error details when finished testing
}else{
    foreach($_SESSION['Sql'] as $i=>$row){
        list($id,$name,$age)=$row;  // apply the $row values to each iterated execute() call
        if(!$stmt->execute()){  // if the execute call fails
            echo "<p>Execute failed: (",$stmt->errno,") ",$stmt->error,"</p>";  // comment this out or remove error details when finished testing
        }else{
            echo "<p>Success on index $i</p>";  // Insert was successful
        }
    }
}