Php 带连接和值的SQL插入

Php 带连接和值的SQL插入,php,sql,xampp,Php,Sql,Xampp,这个问题已经有人问了,但我找不到答案。我搜索了一段时间,发现了这些相关的问题,但它们并没有帮助我理解或回答我的问题 我的问题是如何使用联接在两个表中插入数据。例如(使用php),用户可以输入自己的姓名和喜欢的食物 我将它们存储在一个变量和一个数组中(数组的长度不总是3,如下所示): 这就是我想要存储它们的方式: USERS: UserID name 1 Niels FOODS: FoodID userID name //userID is linked to

这个问题已经有人问了,但我找不到答案。我搜索了一段时间,发现了这些相关的问题,但它们并没有帮助我理解或回答我的问题

我的问题是如何使用联接在两个表中插入数据。例如(使用php),用户可以输入自己的姓名和喜欢的食物

我将它们存储在一个变量和一个数组中(数组的长度不总是3,如下所示):

这就是我想要存储它们的方式:

USERS:

UserID   name
1        Niels


FOODS:

FoodID userID name     //userID is linked to UserID in users table
1      1      apple
2      1      pear
3      1      banana
我上面粘贴的第一个问题的链接有一个带有连接的插入,但我看不到任何地方可以像普通插入一样放入值

该问题的问题是:

 INSERT INTO orders (userid, timestamp) 
 SELECT o.userid, o.timestamp FROM users u INNER JOIN orders o ON  o.userid = u.id

根据评论部分的情况判断,您的问题是希望有一个更优化的查询过程。现在,您正在使用两个不同的查询来填充两个表,您想知道是否可以以更优化的方式完成这项工作

首先,不可能用一个查询填充两个不同的表

但是,您可以做的是使用事务

这个答案的其余部分将遵循以下假设:您正在使用PHP作为后端脚本语言(正如您标记自己一样)

此外,您是否使用准备好的语句进行查询本身并不明显。如果你没有,我强烈建议你使用事先准备好的陈述。否则,您将面临SQL注入(SQLI攻击)

我将在回答中使用mysqli准备的语句

<?php
// Your input post variables
$name = $_POST['name'];
$foodArray = $_POST['foodArray'];

/*
I'm using a function to handle my queries,
simply because it makes large piles of code easier to read.
I now know that every time the function:
createUserAndFood($name, $foodArray);

is called, that it will populate my user and food table.
That way I don't have to worry about writing all the code multiple times.
*/
function createUserAndFood($name, $foodArray){
    // food array values
    $foodValues = array_values($foodArray);

    // DB variables
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if($conn->connect_error){
      die("Connection failed: " . $conn->connect_error);
    }

    /*
    Stops the query from auto commiting,
    I'll explain later, you can "maybe" disregard this.
    */
    $conn->autocommit(FALSE);

    // Declare the query
    $sql = "INSERT INTO userTable(name) VALUES(?)";

    // Prepare and bind
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $name);

    // Execute the query
    $stmt->execute();

    // Fetch last inserted id
    $lastID = $conn->insert_id;

    $sql = "INSERT INTO foodTable(userId, food) VALUES(?, ?)";
    $stmt = $conn->prepare($sql);

    for($i = 0; $length = count($foodValues) > $i; $i++){
        $stmt->bind_param("is", $lastID, $food);
        $food = $foodValues[$i];
        $stmt->execute();
    }
    // Commits the query / queries
    $conn->commit();

    // Close connection
    $stmt->close();
    $conn->close();
}
?>

您的底层数据库服务器是什么?我目前正在使用xampp来承载我的locallyNo问题。在查询中它应该可以工作,检查表中的任何约束,或者尝试在临时表上使用“with”和纯select语句。我知道查询可以工作,它是从另一个问题复制的,但是我不明白这个查询将如何插入值,因为查询中没有“values('niels')。如果您要求用一个查询插入到两个不同的表中,那么这是不可能的。不过,还有其他方法,请参考:是的,我的问题主要是为了避免不完整的数据集,感谢您详细而有益的回答。
<?php
// Your input post variables
$name = $_POST['name'];
$foodArray = $_POST['foodArray'];

/*
I'm using a function to handle my queries,
simply because it makes large piles of code easier to read.
I now know that every time the function:
createUserAndFood($name, $foodArray);

is called, that it will populate my user and food table.
That way I don't have to worry about writing all the code multiple times.
*/
function createUserAndFood($name, $foodArray){
    // food array values
    $foodValues = array_values($foodArray);

    // DB variables
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if($conn->connect_error){
      die("Connection failed: " . $conn->connect_error);
    }

    /*
    Stops the query from auto commiting,
    I'll explain later, you can "maybe" disregard this.
    */
    $conn->autocommit(FALSE);

    // Declare the query
    $sql = "INSERT INTO userTable(name) VALUES(?)";

    // Prepare and bind
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $name);

    // Execute the query
    $stmt->execute();

    // Fetch last inserted id
    $lastID = $conn->insert_id;

    $sql = "INSERT INTO foodTable(userId, food) VALUES(?, ?)";
    $stmt = $conn->prepare($sql);

    for($i = 0; $length = count($foodValues) > $i; $i++){
        $stmt->bind_param("is", $lastID, $food);
        $food = $foodValues[$i];
        $stmt->execute();
    }
    // Commits the query / queries
    $conn->commit();

    // Close connection
    $stmt->close();
    $conn->close();
}
?>
BEGIN;
INSERT userTable SET name = '$name';
SET @lastID = LAST_INSERT_ID();
INSERT foodTable SET id = @lastID, food = '$food';
COMMIT;