php - 如何将两个 PDO 语句组合起来插入数据库?

标签 php database arrays pdo

我希望将一个 pdo 语句的输出与另一语句的数组数据一起使用。目前,两组语句单独工作都很好,但我不知道如何将输出合并到数据库上的一个表中。

我尝试更新的数据库表有 3 列:recipe_iditem_numberquantity

我需要的是 $recipeID 用作主要 recipe_id 以及数组的输出来填充其他两列。希望我说得有道理并且有人可以提供帮助,我正在使用的代码如下所示并带有注释:

<?php
        //MySQL Database Connect
        require 'config.php';

        //Takes form input for recipe title for insert to the recipe table
        $name = $_POST["recipeName"];

        //Stored procedure inputs the recipe name to the recipe table and outputs a recipe_id which is to be passed into recipe item table below
        $stmt = $dbh->prepare( "CALL sp_add_recipe(:name, @output)" );
        $stmt->bindParam(':name', $name, PDO::PARAM_STR);

        //Execute Statment
        $stmt->execute();

        //$recipeID variable stores recipe_id outputted from the stored procedure above
        $recipeID = $dbh->query( "SELECT @output" )->fetchColumn(); 

        //Insert places the values from $recipeID, item_number & quantity into the recipe_item table
        $stmt = $dbh->prepare('INSERT INTO recipe_item (recipe_id, item_number, quantity) VALUES (:recipeID,?,?)');
        $stmt ->bindParam(':recipeID',$recipeID, PDO::PARAM_STR);

        //Ingredients variable combines array values from HTML form
        $ingredients = array_combine($_POST['recipe']['ingredient'], $_POST['recipe']['quantity']);

        //Each value from the form is inserted to the recipe_item table as defined above
        foreach($ingredients as $name => $quantity)
        {
            $stmt->execute(); //I would like to insert $recipeID to my database with each line of the array below.
            $stmt->execute(array($name, $quantity)); 
        }
    ?>

最佳答案

$stmt = $dbh->prepare('INSERT INTO recipe_item (recipe_id, item_number, quantity) VALUES (:recipeID,:number,:quantity)');

//remove the bindParam() call for recipeId

$ingredients = array_combine($_POST['recipe']['ingredient'], $_POST['recipe']['quantity']);

foreach ($ingredients as $name => $quantity) {
    $bound = array(
        'recipeID' => $recipeID,
        'number' => $name, // ?? This is what your codes does at the moment, but looks weird
        'quantity' => $quantity
    );
    $stmt->execute($bound);
}

关于php - 如何将两个 PDO 语句组合起来插入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659962/

相关文章:

php - 我还应该做些什么来清理用户输入?

php - sql Like搜索如何根据搜索结果从一张表中提取数据

php - 使用 Codeigniter 生成包含 2 个表的 CSV

python - MySQL:使用 "SELECT INTO OUTFILE"时对字符串进行 Wiered 切割

arrays - 快速切换转换时出错

php - 在 foreach 的每次迭代中创建新数组

mysql - 托管在 AWS 上以访问多个外部数据库的应用程序

sql-server - 查找一组 3d 点的相关子集

ruby - 如何对整数数组进行排序,同时保持相同的元素彼此分开?

PHP:数组中的多列搜索