【问题标题】:How to Implode $_SESSION ARRAY then insert into Mysql如何 Implode $_SESSION ARRAY 然后插入 Mysql
【发布时间】:2018-02-02 22:45:11
【问题描述】:

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

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

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

SESSION 中存储的数据

$_SESSION['Sql'] = $result;

从 SESSION 或 Result 完美打印

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 

【问题讨论】:

  • MYSQL_NUM 返回数字键,你要MYSQLI_ASSOC
  • 我改为 MYSQLI_ASSOC & MYSQLI_BOTH。同样的错误。谢谢你的帮助。
  • 您对 SQL 注入持开放态度。我会创建一个类来构建您的查询(有关更多信息,请参阅this 答案。然后我会使用动态变量将您的变量映射到适当的列以插入 PDO 或 mysqli。

标签: php mysql arrays session


【解决方案1】:

您可能已关闭通知。

你有一个多维数组,所以你必须更深入地访问才能内爆。

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

这是一个 sn-p,它具有内置的错误检查,包括语句准备、绑定和执行,以便您可以隔离任何问题。 (发帖前我没有测试过,如果有问题请留言。我不希望任何人复制错字或有缺陷的代码。)

代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    相关资源
    最近更新 更多