猿问

将数据插入到具有外键字段的php表中

我通过添加反馈表来修改现有项目。我需要将反馈表单数据存储到一个名为feedback_formtb的表中。我编写了 sql 代码来创建这个表。还有一个已经创建的表调用profile_request,我想从这个profile_request表中获取一个外键。因此,我将 request_id 字段添加为外键。(我无权编辑 profile_request 表,因为该部分已经开发)我创建了一个名为feedback_test.php的文件。


现在我想将反馈表单数据插入到 feedback_formtb 表中。我按照我的理解做了。但是由于外键,我不确定这个 sql 插入查询是否正确,我是否正确地将数据插入到表中。(我没有用户界面,因为我要求将此反馈表单添加到现有项目中)。如果有人可以帮助我判断这在哪里可以,真的很感谢您的帮助。提前致谢。


===============feedback_formtb 表创建===================


DROP TABLE IF EXISTS `feedback_formtb`;

 CREATE TABLE IF NOT EXISTS `feedback_formtb` (

 `fid` int(10) NOT NULL,

 `job_complete` tinyint(2) NOT NULL,

 `satisfaction` double NOT NULL,

 `reason` int(20) NOT NULL,

 `comment` text NOT NULL,

 `request_id` int(10) NOT NULL,

  PRIMARY KEY (`fid`),

  FOREIGN KEY (`request_id`) REFERENCES profile_requests(`id`)

 )ENGINE=InnoDB DEFAULT CHARSET=latin1;

=============profile_requests 表=================


DROP TABLE IF EXISTS `profile_requests`;

CREATE TABLE IF NOT EXISTS `profile_requests` (

  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),

  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),

  `created_by` int(10) UNSIGNED NOT NULL,

  `updated_by` int(10) UNSIGNED NOT NULL,

  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,

  `user_id` int(10) UNSIGNED NOT NULL,

  `profile_id` int(10) UNSIGNED NOT NULL,

  `expected_date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',

  `lat` float UNSIGNED NOT NULL,

  `lng` float UNSIGNED NOT NULL,

  `city_id` int(11) NOT NULL,

  `message` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,

  `state` tinyint(3) UNSIGNED NOT NULL DEFAULT 1 COMMENT '1:new request, 2:accepted,3:rejected',

  `urgent` tinyint(3) UNSIGNED NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=latin1;



Cats萌萌
浏览 124回答 1
1回答

米脂

您不需要子查询。只需$request_id用作列的值。 $ips = $mysqli->prepare('    INSERT INTO feedback_formtb (job_complete, satisfaction, reason, comment, request_id)     VALUES (?, ?, ?, ?, ?)'); 外键约束将确保它$request_id是有效的。如果您尝试插入 中不存在的 ID,profile_requests则会出现错误。
随时随地看视频慕课网APP
我要回答