将数据插入到通过外键连接到另一个表的表中

时间:2013-05-11 02:37:38

标签: php mysql

我遇到了一个问题,我在MYSQL中创建了两个表,其中一个表是bookticket,另一个表是customer表。

客户表 的 CUSTOMER_ID(PK)下,全名,matric_id,ic_no,性别,地址,邮编,状态,hp_number,tel_number,用户名,密码,repeatpassword。

booktickect表 的 TICKET_ID(PK)下,衬垫,方向,从,f_date,f_time,目的地,t_date,t_time,TOTAL_PRICE,的 CUSTOMER_ID(FK)

所以现在我注册并以用户身份登录后,如何创建一个php代码来输入bookticket数据,它将根据我在其中实现的customer_id外键自动分配给当前登录的用户我的bookticket table.Thank提前。

很抱歉没有在我之前的帖子中提供我的PHP代码。我编辑了我的问题。 :)

<?php

 echo "<h1>Booking</h1>";

 $submit = $_POST['submit'];

 //ticket booking form data

 $liner     = strip_tags($_POST['liner']); 
 $direction     = strip_tags($_POST['direction']); 
 $from      = strip_tags($_POST['from']); 
 $f_date        = strip_tags($_POST['f_date']); 
 $f_time        = strip_tags($_POST['f_time']); 
 $destination   = strip_tags($_POST['destination']); 
 $t_date        = strip_tags($_POST['t_date']); 
 $t_time        = strip_tags($_POST['t_time']); 
 $total_price       = strip_tags($_POST['txttotal']);

 if ($submit)
 {  

 //check the direction selected by user

if ($direction == "return")
{

//check for existance

    if($liner && $direction && $from && $f_date && $f_time && $destination && $t_date &&      $t_time && $total_price )
            {

             $connect  = mysql_connect("localhost" ,"cc11205","11205");
                mysql_select_db("cc11205");

              $queryreg = mysql_query("

              INSERT INTO bookticket VALUES ('','$liner','$direction','$from','$f_date','$f_time','$destination','$t_date','$t_time','$total_price','');


              ");

              die("Your booking details has been succesfully inserted into the database.Please <a href='customer.php'>Click here</a> to go to the main page to view your booking");

            }

        else 

            echo "Please fill in <b>all</b> fields!";

}
else if ($direction == "oneway")
{
    if($liner && $direction && $from && $f_date && $f_time && $destination && $total_price  )
            {
               $connect  = mysql_connect("localhost" ,"cc11205","11205");
                mysql_select_db("cc11205");

              $queryreg = mysql_query("

              INSERT INTO bookticket VALUES ('','$liner','$direction','$from','$f_date','$f_time','$destination','','','$total_price','');


              ");
              die("Your booking details has been succesfully inserted into the database.Please <a href='customer.php'>Click here</a> to go to the main page to view your booking");

            }
        else 
            echo "Please fill in <b>all</b> fields!";

}
 }
 ?>

1 个答案:

答案 0 :(得分:-1)

我假设您想知道如何获取customer表的第一个查询的生成密钥。您可以使用mysql_insert_id。下面是一个例子。

$rs = mysql_query($insert_sql_for_customer);
$customer_id = mysql_insert_id();

$booking_sql = "INSERT INTO bookticket (customer_id, field1, field2, ...) VALUES ($customer_id, $val1, $val2, ...);
mysql_query($booking_sql);