Skip to content
Advertisement

How to insert array as key => value with string value into sql using php [closed]

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);
 }

I am having just a small problem with the name array, when i perform the above code every row’s member values takes the value of

What i am getting

member
-----
name1,name2,name3,name4
name1,name2,name3,name4
name1,name2,name3,name4
name1,name2,name3,name4

What i want is this

member
-----
name1
name2
name3
name4

Note: Every Other Column is perfectly inserted and I would take into account the SQL Injection security later on.

Advertisement

Answer

I think you just need to keep $name as an array, don’t implode it back into a string, and then loop over that. I have no idea what is in $give and others. I see that they are arrays but I don’t understand their relationship to $name. The below code does this and inserts 16 records (assuming 4 names):

// Store names in an array
$names = [];
foreach ($_SESSION['s'] as $key => $value) {
    $names[] = $value;
}

$conn = mysqli_connect("localhost", "root", "", "slashbill");
$sql = 'INSERT INTO slashbill (member,give,receive,paid) VALUES (?,?,?,?)';

// Loop over names
foreach ($names as $name) {
    for ($x = 0; $x <= 3; $x++) {
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            die('Could not prepare statement');
        }
        if (!$stmt->bind_param('ssss', $name, $give[$x], $receive[$x], $paid1[$x])) {
            die('Could not bind statement');
        }
        if (!$stmt->execute()) {
            die('Could not execute statement');
        }
    }
}

If, however, there’s some magic relation between the session data and your other variables, and you really want to only insert 4 rows, then this version which still track $x can be used.

// Store names in an array
$names = [];
foreach ($_SESSION['s'] as $key => $value) {
    $names[] = $value;
}

$conn = mysqli_connect("localhost", "root", "", "slashbill");
$sql = 'INSERT INTO slashbill (member,give,receive,paid) VALUES (?,?,?,?)';

// Loop over names
for ($x = 0; $x <= count($names); $x++) {
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die('Could not prepare statement');
    }
    if (!$stmt->bind_param('ssss', $names[$x], $give[$x], $receive[$x], $paid1[$x])) {
        die('Could not bind statement');
    }
    if (!$stmt->execute()) {
        die('Could not execute statement');
    }
}

I know you said you’ll worry about escaping it later, but I just switched it over to a prepared statement any because it is much easier to ready for everyone.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement