Jan Kocvik
Jan Kocvik

Reputation: 41

Is possible to INSERT List instead of String?

I'm trying to learn more with SQL and I am trying to INSERT a List of Numbers linked with 1 ID (row).

Now I figured out how to use List in SELECT, basics like

SELECT * FROM products WHERE catalog_number IN ("CAT1", "CAT2", "CAT3");

and I am trying to do a similar thing but with INSERT

Something like this but this won't work, sadly.

INSERT INTO link_products ('main_product_id', 'linked_product_id') VALUES (124, IN(1,2,3,4,))

Basicly I am trying to do like php foreach command fully in SQL (in phpmyadmin) and I am not even sure if this is possible.

The result should be (in database):

id | main_product_id | linked_product_id
1          124               1
2          124               2
3          124               3
4          124               4 

Upvotes: 1

Views: 104

Answers (3)

KEYUR THUMMAR
KEYUR THUMMAR

Reputation: 16

<?php
    $servername="localhost";
    $username="root";
    $password="";
    $dbname="demon";
    //CREATE CONNECTION
    $conn=new mysqli($servername,$username,$password,$dbname);
    //CHECK CONNECTION
    if ($conn->connect_error) 
    {
        die("connection failed:".$conn->connect_error);
    }
    //$sql="INSERT INTO student(CATEGORY_NAME) VALUES ('PENDA')";
    //isset();
    //Die();
    if (isset($_POST["add"])) 
    {
        $sql="INSERT INTO category(CATEGORY_ID,CATEGORY_NAME) VALUES ('','".$_POST["CATEGORY_NAME"]."')";
        //echo $sql;
        //die();
        $result=$conn->query($sql);
        if ($result===TRUE) 
        {
            echo"NEW RECORD CREATED SUCCESSFULLY";
        }
        else
        {
            echo "ERROR:".$sql."<br>".$conn->error;
        }   
    }   
    $conn->close();
?>
<!DOCTYPE html>
<html>
<head>
    <title>CATEGORY</title>
</head>
<body align="center">
<div>
<form action="" method="POST">
    <td align="center" bgcolor="lightblue"><b>CATEGORY:</b><input type="value" name="CATEGORY_name" WIDTH="1000" value=""/></td>
</br>
</br>
<input type="submit" name="submit" value="submit">
</form>
</div>
</body>
</html>

Upvotes: 0

Stan
Stan

Reputation: 1430

I suppose you'll need something like

INSERT INTO link_products ('main_product_id', 'linked_product_id')
SELECT 124, productId FROM  products WHERE catalog_number IN ("CAT1", "CAT2", "CAT3")

Upvotes: 0

Esteban P.
Esteban P.

Reputation: 2809

Just insert the data like:

INSERT INTO link_products ('main_product_id', 'linked_product_id') 
VALUES (124, 1)
      ,(124, 2)
      ,(124, 3)
      ,(124, 4)
;

Upvotes: 1

Related Questions