【问题标题】:Trying to insert into two tables using php and mysqli尝试使用 php 和 mysqli 插入两个表
【发布时间】:2014-02-08 15:57:05
【问题描述】:

我正在开发一个包含帖子的博客。 我想插入 3 个表格

帖子、类别和 Post_categories(显示帖子的正确类别)

我尝试了所有使用 mysqli 的方法,例如:

$titel  = $_POST['titel'];
$post   = $_POST['post-text'];

$sql=
"INSERT INTO posts (titel, post)
VALUES ('$titel', '$post')
INSERT INTO post_categories (idposts)
VALUES ('". $mysqli->insert_id() ."')
";

if (!mysqli_query($link,$sql))
  {
  die('Error: ' . mysqli_error($link));
  }
echo "1 record added";
mysqli_close($link);

但这没有用。我现在被困了两个小时,我几乎要放弃了。 我真的不知道如何在 Mysqli 中做到这一点。我知道它在 Mysql 中是如何工作的。

希望有人能帮我解决这个问题。

我的表结构如下:

帖子

idposts
标题
发布
添加了

类别

idcategories
类别

post_categories

身份证
idposts
idcategories

【问题讨论】:

  • 在 google 上搜索“mysql insert into multiple tables”。有几个像这样的例子:stackoverflow.com/questions/10043887/… 基本上,如果你不做一个“存储过程”,那是不可能的。您需要插入第一个,然后是第二个,依此类推。

标签: php mysqli insert insert-id


【解决方案1】:

由于您要插入多个表,因此也请尝试使用事务。在执行查询之前,您也无法获取 mysql_insert_id()。

mysqli_autocommit($link, FALSE);
$sql = "INSERT INTO posts (titel, post) VALUES ('".$titel."', '".$post."')";
if (mysqli_query($link, $sql ) === TRUE) {
  $postId = mysqli_insert_id($link);
   $sql1 = "INSERT INTO post_categories (idposts) VALUES ('".$postId."')";
   mysqli_query($link, $sql1 );
}
if (!mysqli_commit($link)) { //commit transaction
   print("Table saving failed");
    exit();
}

【讨论】:

  • 这就像一个魅力!谢谢先生。我对 Mysqli 还很陌生,因为我上一个“大”项目是用旧的烂 mysql。
【解决方案2】:

你不能使用 mysqli_query 同时执行两个查询,如果你真的想这样做,你应该使用mysqli_multi_query

【讨论】:

  • 这是插入两个表的最佳方式吗?我不确定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 2011-09-04
  • 2019-04-02
  • 1970-01-01
相关资源
最近更新 更多