如何从表中获取id并在php语句中插入另一个表?

时间:2018-04-13 17:04:43

标签: php mysqli

如何从商店获取id并使用prepare语句插入另一个表?

我是否必须进行2次查询?

有人能举例说明吗?

图像表看起来像这样

image_id image_name

项目表

id item_name 

我的插入代码

    if(empty($title_err) && empty($details_err) && empty($image_err) && empty($cat_id_err)){
        // Prepare an update statement
        $sql = "INSERT INTO adverts (cat_id, store_id, user_id, title, details, image, seo_url, hits, date, active) VALUES (?, ?, ?, ?, ?, ?, ?, ?,? ,?)";
        if($stmt = $conn->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("iiissssiss", $param_cat_id, $param_store_id, $param_user_id, $param_title, $param_details, $param_image, $param_seo_url, $param_hits, $param_date, $param_active);

            // Set parameters
            $param_cat_id = htmlspecialchars($cat_id);
            $param_store_id = htmlspecialchars($store_id);
            $param_user_id = htmlspecialchars($_SESSION['id']);
            $param_title = htmlspecialchars($title);
            $param_details = htmlspecialchars($details);
            $param_image = htmlspecialchars($filedestination);
            $param_seo_url = seo_url($title);
            $param_hits = htmlspecialchars(1);
            $param_date = htmlspecialchars($date);
            $param_active = htmlspecialchars(Y);

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Records updated successfully. Redirect to landing page
                header("location: index.php");
                exit();
            } else{
                echo "Something went wrong. Please try again later.";
            }
        }

        // Close statement
        $stmt->close();
    }

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

我想从商店表中获取ID并插入广告

我做了第二次查询,但是它没有工作

// Prepare a select statementwhere userid=?
    $sql = "SELECT * FROM stores WHERE store_id=? ORDER BY store_id DESC";
    if($stmt = $conn->prepare($sql)){
        // Bind variables to the prepared statement as parameters
        $stmt->bind_param("i", $param_store_id);
        if($stmt->execute()){
            $result = $stmt->get_result();
            if($result->num_rows == 1){
                /* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
                $row = $result->fetch_array(MYSQLI_ASSOC);

                // Retrieve individual field value
                $store_id = $row["store_id"];
                $store_name = $row["store_name"];
            } else{
                // URL doesn't contain valid id. Redirect to error page
                header("location: error.php");
                exit();
            }
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }

    // Close statement
    $stmt->close();

    // Close connection
    $conn->close();

0 个答案:

没有答案