从2个不同的表中获取数据并将其插入一个表中

时间:2017-04-22 14:07:01

标签: php mysql sql join

我正在尝试创建一个酒店预订系统,现在我无法将预订信息插入我的数据库。

    if(isset($_POST['submit'])){

    $c_username = $_POST['c_username'];
    $r_name = $_POST['r_name'];
    $checkin = $_POST['checkin'];
    $checkout = $_POST['checkout'];
    }

我只提供' c_username ',' r_name ',' checkin ','结帐'来自HTML表单标记.... c_id r_id 应该从另外两个名为 cust_info 的数据库中获取,其中 c_id找到住宿 r_id 所在的位置。你可以从下面看到我试图获得它,如下所示。但是,当我尝试将数据插入数据库而不注释第二个和第三个查询时,将不会插入任何数据,它将在行上返回错误 $query .= "VALUES ( '$c_id', '$c_username', '$r_id', '$r_name', '$checkin', '$checkout' )";

/*$query = "SELECT c.c_id, a.r_id FROM 'cust_info' c JOIN 'accomodation' a WHERE c_username LIKE '{$c_username}' AND r_name LIKE '{$r_name}'";*/

$query = "SELECT c_id FROM cust_info WHERE c_username LIKE '{$c_username}'";

$query = "SELECT r_id FROM accomodation WHERE r_name LIKE '{$r_name}'";

$query = "INSERT INTO reserve( c_id, c_username, r_id, r_name, checkin, checkout)";
$query .= "VALUES ( '$c_id', '$c_username', '$r_id', '$r_name', '$checkin', '$checkout' )";

$create_post_query = mysqli_query($con, $query);

当我将前三个查询更改为注释时,这就是我的代码目前的样子。该程序可以插入“ c_username ”,“ r_name ”,“ checkin ”,“结帐”的数据进入数据库。

谢谢

1 个答案:

答案 0 :(得分:0)

我希望这会对你有所帮助

$query = "SELECT c_id FROM cust_info WHERE c_username LIKE '{$c_username}'";
$query_res = mysqli_query($con, $query);
$c_id = mysqli_fetch_array($query_res);


$query2 = "SELECT r_id FROM accomodation WHERE r_name LIKE '{$r_name}'";
$query_res = mysqli_query($con, $query2);
$r_id= mysqli_fetch_array($query_res);


$query = "INSERT INTO reserve( c_id, c_username, r_id, r_name, checkin, checkout)";
$query .= " VALUES ( $c_id, $c_username, $r_id, $r_name, $checkin, $checkout )";

$create_post_query = mysqli_query($con, $query);