Search code examples
phpmysqlmysqlidatabase-normalizationmultivalue

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


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

Solution

  • 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);
    }