# Group multiple inputs with the same ID into a single row and insert it into new table

**URL:** <https://www.phphelp.com/t/group-multiple-inputs-with-the-same-id-into-a-single-row-and-insert-it-into-new-table/33641>\
**Category:** MySQL database\
**Created:** [June 22, 2021, 4:39am UTC](https://www.phphelp.com/t/group-multiple-inputs-with-the-same-id-into-a-single-row-and-insert-it-into-new-table/33641 "2021-06-22T04:39:57Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![sashavalentina](https://www.phphelp.com/letter_avatar_proxy/v4/letter/s/8c91f0/32.png) [@sashavalentina](https://www.phphelp.com/u/sashavalentina)\
**Post date:** [June 22, 2021, 4:39am UTC](https://www.phphelp.com/t/group-multiple-inputs-with-the-same-id-into-a-single-row-and-insert-it-into-new-table/33641/1 "2021-06-22T04:39:57Z")

</div>

I have a system that saves the user purchase into a table called ordered\_items. Where the purchase data will be saved into this table if the product stock available is more than the quantity that the user intended to purchase. The way how the system saved the data is by id. Which means if the USER A bought one iPad, two iPhone , USER B bought one AirPods, Iphone and an Ipad, USER C bought three IMac, two Macbook. The data that store in the table will look like this

 ![image](https://www.phphelp.com/uploads/default/original/2X/c/cdf2bb160bd6d707ab82a4a1a3d60cc6177d583b.png)  
Now I created another table called the **invoice\_price** table where i want the above data to be group according to the order\_id in the ordered\_items table and be inserted into this new table called **invoice\_price**. So after the data is grouped, the data saved in the database will look something like this  
 ![image](https://www.phphelp.com/uploads/default/original/2X/5/512f277742e4019a3b20baf04141a7d09b852fbc.png)

I tried the below sql but it does not work. Does anyone knows what can i do to achieve what I described above?

```
     if($product_stocks >= $quantity) {
      $osql = "INSERT INTO `ordered_items`(`order_id`, `user_id`, `seller_id`, `product_id`, `quantity`, `purchase_price`) 
      VALUES ('$order_id', '$user_id', '$seller_id', '$product_id', '$quantity', '$purchase_price')";
      if($conn->query($osql)) {
          $product_name = $row['cart_name'];
          $cn_product_name = $row['cn_cart_name'];
          $m_product_name = $row['m_cart_name'];
          $nsql = "INSERT INTO `notifications`(`notification_title`,`cn_notification_title`,`m_notification _title`, `notification_date`, `notification_text`,`cn_notification_text`,`m_notification_text`, `user_id`, `seller_id`, `order_id`, `product_id`, `user_notify`, `seller_notify`, `admin_notify`) 
          VALUES 
          ('New $order_type ','新订单','Pesanan Baharu', '$now', '<b>Order No: #$order_id</b><br>$order_type for $quantity $product_name is Placed Successfully', '<b>订单号: #$order_id</b><br>已成功下单 $quantity 的 $cn_product_name ', 
          '<b>Nombor Pesanan: #$order_id</b><br>Pesanan untuk $quantity $m_product_name anda sudah berjaya ', '$user_id', '$seller_id', '$order_id', '$product_id', 0, 0, 0)";
         
          if($conn->query($nsql)){
             $discountsql = "INSERT INTO invoice_price (order_id) SELECT order_id FROM ordered_items GROUP BY order_id WHERE order_id = '$order_id'";
              $conn->query($discountsql);
          }
  }

```

---

<div class="post-metadata">

**Author:** ![benanamen](https://www.phphelp.com/user_avatar/www.phphelp.com/benanamen/32/287_2.png) [@benanamen](https://www.phphelp.com/u/benanamen)\
**Post date:** [June 22, 2021, 3:52pm UTC](https://www.phphelp.com/t/group-multiple-inputs-with-the-same-id-into-a-single-row-and-insert-it-into-new-table/33641/2 "2021-06-22T15:52:20Z")

</div>

Your code is vulnerable to an SQL Injection Attack. NEVER EVER put variables in your query.

Never trust user input.  
You need to use Prepared Statements.  
Do not create variables for nothing.

---

<div class="post-metadata">

**Author:** ![Callisto](https://www.phphelp.com/letter_avatar_proxy/v4/letter/c/ecb155/32.png) [@Callisto](https://www.phphelp.com/u/Callisto)\
**Post date:** [June 25, 2021, 8:57am UTC](https://www.phphelp.com/t/group-multiple-inputs-with-the-same-id-into-a-single-row-and-insert-it-into-new-table/33641/3 "2021-06-25T08:57:18Z")

</div>

In fact, you should use pdo for all your sql queries.

Check this exemple :

```
function pdo($x, $y){
    $db = new Database();
    $req = $db->prepare("SELECT * FROM table_name WHERE x = '?' AND y = '?'",[$x,$y]);
}

```

You can use pre-existing database pdo class like this :

```
 class Database {

        private $dbName;
        private $dbUser;
        private $dbPass;
        private $dbHost;
        private $pdo;

        public function __construct($dbName, $dbUser, $dbPass, $dbHost) {
            $this->dbName = $dbName;
            $this->dbUser = $dbUser;
            $this->dbPass = $dbPass;
            $this->dbHost = $dbHost;

        }

        private function getPDO() {
            if($this->pdo === null) {
                $pdo = new \PDO("mysql:dbname=".$this->dbName.";host=".$this->dbHost.';charset=UTF8', $this->dbUser, $this->dbPass);
                $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                $this->pdo = $pdo;
            }
            return $this->pdo;
        }

        public function prepare($statement, $values, $one = false) {
            $req = $this->getPDO()->prepare($statement);
            $req->execute($values);
            $req->setFetchMode(\PDO::FETCH_OBJ);
            if($one){
                $datas = $req->fetch();
            } else {
                $datas = $req->fetchAll();
            }

            return $datas;
        }

    }
```
