简体   繁体   English

如何放大$ _SESSION ARRAY然后插入Mysql

[英]How to Implode $_SESSION ARRAY then insert into Mysql

I first retrieve data from TEST database 我首先从TEST数据库检索数据

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

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

Stored Data in a SESSION 在会话中存储数据

$_SESSION['Sql'] = $result;

Prints perfect from SESSION or Result 从SESSION或Result打印完美

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

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

Result - only 2 records in database with 3 columns 结果-数据库中只有2条记录有3列

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

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

)

I then attempt to Insert into TEST2 Database 然后,我尝试插入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);

  }

I receive following ERROR 我收到以下错误

 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 

You probably have your notices turned off. 您可能已关闭通知。

You have a multidimensional array, so you will have to access deeper before you can implode. 您具有多维数组,因此必须先更深入地访问才可以内爆。

See your trouble : 你的麻烦

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

Output: 输出:

<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'

How to prepare your data for the INSERT query: 如何为INSERT查询准备数据:

Code: ( 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

Output: 输出:

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)


The next step in your learning is mysqli prepared statements with placeholders for security reasons. 学习的下一步是出于安全原因, mysqli prepared statements with placeholders

Here is a snippet that has built-in error checking with the statement preparation, binding, and execution so that you can isolate any issues. 这是一个带有语句准备,绑定和执行的内置错误检查的代码段,以便您可以隔离所有问题。 (I didn't test this before posting, if there are any problems please leave a comment. I don't want anyone copying a typo or flawed piece of code.) (我在发布之前没有对此进行测试,如果有任何问题,请发表评论。我不希望任何人复制打字错误或有缺陷的代码。)

Code: 码:

$_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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM