如何使用 php 将数组作为键 => 具有字符串值的值插入到 sql

foreach($_SESSION['s'] as $key=>$value){

  $name[]="'".$value."'";

}

$name=implode(",",$name);

$conn= mysqli_connect("localhost","root","","slashbill");


for($x=0;$x<=3;$x++){

  $sql = "INSERT INTO slashbill (member,give,receive,paid) VALUES  

  ($name,'".$give[$x]."','".$receive[$x]."','".$paid1[$x]."')";


  $exe=mysqli_query($conn,$sql);

 }

我对名称数组只有一个小问题,当我执行上面的代码时,每一行的成员值都取值


我得到了什么


member

-----

name1,name2,name3,name4

name1,name2,name3,name4

name1,name2,name3,name4

name1,name2,name3,name4

我想要的是这个


member

-----

name1

name2

name3

name4

注意:所有其他列都已完美插入,稍后我会考虑 SQL 注入安全性。


牧羊人nacy
浏览 101回答 1
1回答

慕哥9229398

我认为你只需要保留$name一个数组,不要将它分解回一个字符串,然后循环遍历它。我不知道里面$give和其他人是什么。我看到它们是数组,但我不明白它们与$name. 下面的代码执行此操作并插入 16 条记录(假设有 4 个名称):// Store names in an array$names = [];foreach ($_SESSION['s'] as $key => $value) {&nbsp; &nbsp; $names[] = $value;}$conn = mysqli_connect("localhost", "root", "", "slashbill");$sql = 'INSERT INTO slashbill (member,give,receive,paid) VALUES (?,?,?,?)';// Loop over namesforeach ($names as $name) {&nbsp; &nbsp; for ($x = 0; $x <= 3; $x++) {&nbsp; &nbsp; &nbsp; &nbsp; $stmt = $conn->prepare($sql);&nbsp; &nbsp; &nbsp; &nbsp; if (!$stmt) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; die('Could not prepare statement');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (!$stmt->bind_param('ssss', $name, $give[$x], $receive[$x], $paid1[$x])) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; die('Could not bind statement');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (!$stmt->execute()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; die('Could not execute statement');&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}但是,如果会话数据和您的其他变量之间存在某种神奇的关系,并且您真的只想插入 4 行,那么$x可以使用仍然跟踪的这个版本。// Store names in an array$names = [];foreach ($_SESSION['s'] as $key => $value) {&nbsp; &nbsp; $names[] = $value;}$conn = mysqli_connect("localhost", "root", "", "slashbill");$sql = 'INSERT INTO slashbill (member,give,receive,paid) VALUES (?,?,?,?)';// Loop over namesfor ($x = 0; $x <= count($names); $x++) {&nbsp; &nbsp; $stmt = $conn->prepare($sql);&nbsp; &nbsp; if (!$stmt) {&nbsp; &nbsp; &nbsp; &nbsp; die('Could not prepare statement');&nbsp; &nbsp; }&nbsp; &nbsp; if (!$stmt->bind_param('ssss', $names[$x], $give[$x], $receive[$x], $paid1[$x])) {&nbsp; &nbsp; &nbsp; &nbsp; die('Could not bind statement');&nbsp; &nbsp; }&nbsp; &nbsp; if (!$stmt->execute()) {&nbsp; &nbsp; &nbsp; &nbsp; die('Could not execute statement');&nbsp; &nbsp; }}我知道你说过你会担心稍后会转义它,但我只是将它切换为准备好的语句,因为它更容易为每个人准备。
打开App,查看更多内容
随时随地看视频慕课网APP