gpt4 book ai didi

php - 在 PHP 函数中传递变量

转载 作者:行者123 更新时间:2023-11-29 13:39:00 25 4
gpt4 key购买 nike

我有这段代码,我将帖子详细信息插入到 mysql 中,并使用另一个函数将照片详细信息添加到 mysql 中。我怎样才能获得帖子的最后一个插入ID作为post_id插入到照片表中

function add_img($whichimg,$title)
{
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "INSERT INTO photos (post_id,title, src) VALUES ('$this->$postid','$title','$whichimg')";
$add_to_db = $conn->query($sql) or die(mysqli_error());
return $add_to_db;
}

function add_post($subject,$content)
{
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "INSERT INTO posts (subject, content) VALUES ('$subject','$content')";
$add_to_db = $conn->query($sql) or die(mysqli_error());
$postid=$mysqli->insert_id;

}

首先调用add_post,然后根据照片数量多次调用add_img

有没有办法将此函数中的 $id 调用到另一个函数中?

解决了$这个->id;

最佳答案

接受函数add_img($whichimg,$title)的另一个参数

作为

   function add_img($whichimg,$title,$postid)

由于您的 add_img 需要 $postid,因此您应该从 add_post($subject,$content) 返回它在函数内部,不要使用 $postid=$mysqli->insert_id; ,而是说 return $mysqli->insert_id;

最后,当您调用这些方法时,请确保执行以下操作:

$id = add_post(<...>,<...>);
add_img(<...>,<...>,$id);

关于php - 在 PHP 函数中传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18369273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com