php - 如何将数据从主键列插入到外键

标签 php mysql codeigniter activerecord

当我插入数据时,我正在从我想要的表单插入数据,因此应该增加在第二列中用作外键的第一列主 ID

我已经尝试过这段代码,但不起作用

第一个表代码

$this->db->query("insert into af_ads (ad_title,ad_pic,ad_description)
 values ('$title','$filepath','$description')");

第二个表代码

   $this->db->query("insert into af_category (cat_type,ad_id_fk)
     values ('$category','ad_id')");

注意:我想将 ad_id 插入 ad_id_fk

最佳答案

试试这个:

// Your first query 
$this->db->query("insert into af_ads(ad_id, ad_title, ad_pic, ad_description)
     values ('', '$title', '$filepath', '$description')");

$ad_id = $this->db->insert_id(); // This returns the id that is automatically assigned to that record

// Use the id as foreign key in your second insert query
$this->db->query("insert into af_category (cat_type,ad_id_fk)
 values ('$category', $ad_id)");

关于php - 如何将数据从主键列插入到外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26030208/

相关文章:

php - 使用factory faker创建的图像在存储在storage/public/images文件夹中时会被删除

php - 间距不适用于带有 if 语句的表 PHP MySQL

mysql - 跟踪 "count"行以外的表行查询的替代方法

php - CodeIgniter phpMyAdmin - 插入名称中有空格的表

php - 如何在 CodeIgniter 4 的助手中编写数据库查询

php - 正则表达式匹配逗号之间的文本

php - 仅播放音频的 video/mp4 类型的 HTML5 视频

mysql - 如果结果不匹配,请从另一个表中选择

php - mysql返回相同的行并集

php - 为什么数据只在 foreach 循环中显示,而在外部是非对象时显示?