Venkat
Venkat

Reputation: 93

How to fetch values from one table and insert the same values in other table

I'm using two buttons "Fetch" and "Submit" in the same page. When I click "Fetch" button am getting the values from one table[ticketgeneration] and display in the form, and fetch is working fine. When I tried to insert the fetch records to another table[details] the records is not inserting.

HTML PART
<div class="col-sm-3">
             <center><input type="submit" name="fetch" id="fetch" class="btn btn-primary" value="Fetch Records" style="padding: 4px 10px 4px 10px;float:right;"></center>
        </div>
         <div class="col-sm-3">
                <center><input type="submit" name="submit" id="submit" class="btn btn-primary" value="Submit" style="padding: 4px 10px 4px 10px;float:left;"></center>
        </div>
PHP PART
if (isset($_POST['fetch'])) {
       $ticketid1 = $_POST['tid'];
        $sel = "select * from ticketgeneration where ticket_id='$ticketid1'";
        $res = mysqli_query($conn,$sel);
        $row = mysqli_fetch_array($res);
        
    }

The above code is fetching the values from "ticketgeneration" table and display in the textbox

<input type="text" class="form-control" name="custname" id="custname" value="<?php echo $row['customer_name'];?>">

When I tried to insert the fetched values to other table [details] it is not inserting.

if(isset($_POST['submit'])) {
        $ticketgendate = $_POST['date'];
       $ticketid = $row['ticket_id'];
        $customername = $row['customer_name'];
...
$ins = "insert into details (date,ticket_id,customer_name,...)values (('$ticketgendate','$ticketid','$customername',...)";
$res = mysqli_query($conn,$ins);

am I missing condition somewhere...

Upvotes: 0

Views: 531

Answers (2)

kiran_ray
kiran_ray

Reputation: 295

Any data insert from one table to another table used this query.

$query = 'insert into table_name (col1, col2, columnList....) select col1, col2, columnList... from table_name where ticket_id = $id';

You can add other column in select statement, just mention column name in insert query statement.

Thanks!!!

Upvotes: 1

N.S
N.S

Reputation: 139

You need to use below query to insert data in your case. Use only $ticketid1 to insert data.

$ins = "insert into details (date,ticket_id,customer_name,...) select date,ticket_id,customer_name,... from ticketgeneration where ticket_id='$ticketid1'";

And then run your query, it will insert selected data directly without doing extra code.

Upvotes: 1

Related Questions