0

i Want to insert each array element into new row in mysql db

<?php
   if(isset($_SESSION['user'])){
      echo "<body>
            <form method='GET'>
            <input type='text' id='search-box' name='item'>
            <button type='submit' name='add'>add</button>
            <button type='submit' name='place'>place</button>
            </form>
            </body>";
    if(isset($_GET['add'])){
       $item = $_GET["item"];
       array_unshift($_SESSION['menu1'], $item);
    }
   if(isset($_GET['place'])){
       echo implode(",", $_SESSION['menu1']);
    }
   }
   else{
      echo "you are not logged in";
   }
 ?>

The above code outputs an array in which each element is separated by comma, but i want to insert each element into a new row

  • See [implode()](https://www.php.net/manual/en/function.implode.php). If you don't want the array joined by commas, you may want to remove that part. – showdev Jul 27 '19 at 09:16
  • There was no coding attempt to insert, so a generalised duplicate is suitable for closure. You should not be using the GET method to send data bound for the database. – mickmackusa Jul 27 '19 at 09:55

1 Answers1

0

If you have a large set of values in the array to be inserted in the database, I suggest you to segment the query.

You can use Prepared Statement

$stmt = $mysqli->prepare("INSERT INTO something ( id , title , description) VALUES ( DEFAULT , ?, ?)");

foreach( $item_array as $item ){
    $stmt->bind_param( $item->title , $item->description);
    $stmt->execute();
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Kiran Maniya
  • 8,453
  • 9
  • 58
  • 81
  • 2
    You might consider using [Prepared Statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php). Also see [why MySQLi prepared statements?](https://stackoverflow.com/questions/5200238/why-mysqli-prepared-statements). – showdev Jul 27 '19 at 09:20