How to insert multiple values in a specific field in a table using mysqli?

3.1k views Asked by At

I am working on a project and I I have a scenario like this: I have many field in my table :

table_name : transaction_tbl
-id
-name
-description
-ref_number : text(datatype)

In my inserting here is my code:

    $sql = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`) VALUES ('$name','$desccription',$ref_number)";

if ($conn->query($sql) === false){
                    trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
                }else {
                    echo "Successful ! Data is inserted in database ^__^" ;

                }

As the name itself ref_number or reference number, so there will be a time that I will have a lot of reference number,how can I let it insert if it will have multiple values? Thanks :)

UPDATE :

I want something like this :

name    description            ref_number
bag     to be use               10359435846 
                               05438547656
                               035848576
2

There are 2 answers

8
Demonyowh On BEST ANSWER

for what purpose ? why don't you just insert a new row with the same name and description with different ref_number ?

but if you would like that , you can concatenate your new ref_number with the existing ..

first check if it already exist get its value then concatenate the new ref number .. or if it doesn't exist , insert a new row ..

$sql = "SELECT `ref_number` FROM `transaction_tbl`
WHERE `name`='$name' AND `description`='$description'";


$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
    $row = mysql_fetch_array($query);
    $new_ref = $row['ref_number'] . '|' . $ref_number;
    $upd = "UPDATE `transaction_tbl` SET `ref_number`='$new_ref'
            WHERE `name`='$name' AND `description`='$description'";
}
else
{
    $ins = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`)
            VALUES ('$name','$desccription',$ref_number)";
    mysql_query($ins);
}
0
kuma  DK On

Its not a good practice to have multiple values in one cell (and you should never unless there is a serious reason). It violates basic db rules. Just split this to two tables and assign foreign keys to link them up.

Learn db normalization. There are lot of examples. In here you need to take your un-normalized (0NF) table to at least to 1st normalized level (1NF). But its advised to make it normalized at least up to 3rd level

google for db normalization tutorials. As you request below image will give you an idea(field names are not same as in your question).

0NF to 1NF

First insert the values to table1(Member table) and get the insert id in php use $iid = mysqli_insert_id()

Next add the multiple values as seperate rows into the second table(database table) along with the primary key obtained in first step.

Keep in mind this is not a tutorial site. find more info on net.