0

I need some help coding this. I want to insert each $value element from $_SESSION into $key coloumn(these were created after $key). Something like

foreach ($_SESSION as $key => $value) {
    // "INSERT INTO test (".$value.") VALUES (". $key.")";
}

i was looking at Best way to INSERT many values in mysqli? but i dont quite get it Since im useing mysqli it has to be objects

Community
  • 1
  • 1
Newb
  • 27
  • 1
  • 6

1 Answers1

0

You've got the general idea. Try this:

$conn = mysqli_connect($host, $user, $password, $database);
foreach ($_SESSION as $key => $value) {
    $query = "INSERT INTO test (".$value.") VALUES (".$key.")";

    mysqli_query($conn, $query);
}

And that should be it. This will loop through each item, then it will define and execute a query. Pretty simple.

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • Ok this works, but each insert goes into new row, meaning there is only 1 piece of data filled in in each row – Newb Sep 26 '14 at 07:46
  • Well yes, it would do that. Look at your insert statement. You only send 1 value (aka 1 column) to the database. You would need to change it to an `INSERT INTO test (column, column, column, etc...) VALUES (value, value, value, etc...)` – Tim Lewis Sep 26 '14 at 13:05
  • It is open door for poor performance and sql injections. you should use prepared statements to insert in batch – Iłya Bursov Sep 29 '14 at 18:05