php - 在MySql php中将数据存储到带有外键的2个表中

标签 php mysql database

我在MySql中有两个表,分别是表1和表2。因为我想通过userID将表1链接到表2。但是,我推出的功能不起作用。

MySQl 表如下:

enter image description here

enter image description here

在我的例子中,userId 将是链接这两个表的外键。 但是,我的功能不起作用。 这是我的功能如下:

function insert() {
    function adduserdetails($con, $accountId, $name, $contact) {

        $query = "insert into userdetails(accountId,name,contact) 
            values('$accountId','$name','$contact')";
        //echo "{$sqlString}";



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


        if ($insertResult) {
            echo " Applicant Detail Added !<br />";
            echo "<a href='index.php'>Back to Home</a>";
        } else {
            echo " Error !";
            echo "{$query}";
            //header('Location: post.php');
        }
    }

}

if ($con->query($query) === TRUE) {
    $last_id = $con->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $query . "<br>" . $con->error;
}

function adduseremployment($con,$last_id,$occupationMain,$comapny){

    $query1 = "insert into useremployment(userId,Occupation,company) 
            values('$last_id',$occupationMain','$comapny')";            
                 //echo "{$sqlString}";


                 $insertResult = mysqli_query($con, $query1);


                 if($insertResult){
                     echo " Applicant Detail Added !<br />";
                     echo "<a href='index.php'>Back to Home</a>";
                 }
                 else {
                     echo " Error !";
                     echo "{$query1}";
                     //header('Location: post.php');
                 }


}

最佳答案

您有垂直表格。

检查下面的代码,

Be remember to prepare statement.

<?php
    function addUser(){
        // parent table.
        $queryParent = ''; // Your userdetails table insert query
        $insertResult = mysqli_query($con, $queryParent);
        $userId = mysqli_insert_id($con); // This is your last inserted userId.

        // child table.
        $queryChild = ''; // Your useremployment table insert query with userId.
        $insertResult = mysqli_query($con, $queryChild);
    }
?>

关于php - 在MySql php中将数据存储到带有外键的2个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44982940/

相关文章:

php - Flex图像通过php到mysql blob

php - Laravel 5.1 工作和听众

php - 使用来自 asp.NET 的连接字符串登录 MySQL 数据库失败

php - mysql varchar with utf8mb4最大字符存储容量

php - 将本地 mySQL 数据库从 Laravel/Homestead 移动到实时站点数据库

php - 通过php连接docker mysql

php - 用作 mysql select/join 属性的随机代码的正确长度是多少

mysql - 数据库组织

php - JSON并上传图片到服务器

database - Entity Framework 6 暂时禁用拦截