search
HomeBackend DevelopmentPHP Tutorial如何向有外键约束的字表中插入记录?

我在mysql中建了两个表
mysql> describe room;
+--------+----------+------+-----+---------+-------+
| Field  | Type     | Null | Key | Default | Extra |
+--------+----------+------+-----+---------+-------+
| name   | char(20) | NO   | PRI | NULL    |       |
| doctor | char(20) | NO   |     | NULL    |       |
+--------+----------+------+-----+---------+-------+
2 rows in set (0.07 sec)

字表是
mysql> describe guahao;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| name  | char(20) | NO   | PRI | NULL    |       |
| sex   | char(10) | NO   |     | NULL    |       |
| age   | char(10) | NO   |     | NULL    |       |
| room  | char(20) | NO   | MUL | NULL    |       |
+-------+----------+------+-----+---------+-------+
4 rows in set (0.00 sec)
其中外键是room,on delete cascade on update cascade

我在命令行中向字表中插入数据没有问题,结果是
mysql> insert into guahao values
    -> ('小张','男','30','皮肤科');
Query OK, 1 row affected (0.04 sec)

mysql> select * from guahao;
+--------+-----+-----+-----------+
| name   | sex | age | room      |
+--------+-----+-----+-----------+
| 王八 | 女 | 60  | 内科    |
| 钱二 | 男 | 40  | 脑科    |
| 赵一 | 男 | 20  | 五官科 |
| 孙三 | 女 | 35  | 骨科    |
| 寂寞 | 男 | 22  | 骨科    |
| 小张 | 男 | 30  | 皮肤科 |
| 小明 | 男 | 25  | 脑科    |
| 李四 | 男 | 30  | 皮肤科 |
+--------+-----+-----+-----------+
9 rows in set (0.00 sec)
但是我用PHP的时候,同样的插入语句,却会报错,错误信息如下:
Cannot add or update a child row: a foreign key constraint fails (`clinic`., CONSTRAINT `#sql-9e_13_ibfk_1` FOREIGN KEY (`room`) REFERENCES `room` (`name`) ON DELETE CASCADE ON UPDATE CASCADE)
请大神帮我看看问题在哪!跪求!哭了,问过一次,没解决问题。


回复讨论(解决方案)

为什么这个问题没有人回复?不是很难的问题啊

1、你的操作系统?
2、你的程序使用的字符集?
3、为了给帮助你的人提供便利,你应该给出
a、建表的 sql 指令
b、供测试用的 php 代码



吼吼,快来人解答~~

1、你的操作系统?
2、你的程序使用的字符集?
3、为了给帮助你的人提供便利,你应该给出
a、建表的 sql 指令
b、供测试用的 php 代码
1. 操作系统是MAC OS X
2. 字符集是
mysql> show variables like 'character%';
+--------------------------+--------------------------------------------------------+
| Variable_name            | Value                                                  |
+--------------------------+--------------------------------------------------------+
| character_set_client     | latin1                                                 |
| character_set_connection | latin1                                                 |
| character_set_database   | latin1                                                 |
| character_set_filesystem | binary                                                 |
| character_set_results    | latin1                                                 |
| character_set_server     | latin1                                                 |
| character_set_system     | utf8                                                   |
| character_sets_dir       | /usr/local/mysql-5.1.63-osx10.6-x86_64/share/charsets/ |
+--------------------------+--------------------------------------------------------+
8 rows in set (0.08 sec)
用于插入数据库的数据是从一个编码为UTF-8的HTML页面用post方法传到一个编码同样为UTF-8的PHP文件。


3.  

建表的sql指令是在终端输入的  如下
mysql> create table room(name char(20) not null primary key, doctor char(20) not null) type=innodb;
Query OK, 0 rows affected, 1 warning (0.05 sec)

mysql> create table guahao    -> (name char(20) not null primary key,    -> sex char(10) not null,
    -> age char(10) not null,
    -> room char(20) not null,
    -> foreign key(room) references room(name) on delete cascade on update cascade)
    -> type=innodb;
Query OK, 0 rows affected, 1 warning (0.41 sec)

PHP代码是

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=GB18030"><title>医院门诊挂号系统</title><style type="text/css">	#table	{		margin-right: auto;		margin-left: auto;	}</style></head><body style="text-align: center"><?php$pname=$_POST['pname'];$psex=$_POST['psex'];$page=$_POST['page'];$room=$_POST['room'];if (empty($pname)||empty($psex)||empty($page)){?><p style="text-align:center">请输入完整的患者信息!</p><form method="post" action="Guahao.php"><table id="table"><tr><td>姓名:</td><td><input type="text" id="pname" /></td><td>性别:</td><td><input type="text" id="psex" /></td></tr><tr><td>年龄:</td><td><input type="text" id="page" /></td><td>科室:</td><td><input type="text" id="room" /></td></tr></table><input type="reset" value="重置" id="reset" style="width:100px;height:20px" /><input type="submit" value="挂号" id="submit" style="width:100px;height:20px" /></form><?php}else{	$db = new mysqli('127.0.0.1','clinicadmin','clinicadmin','clinic');	if (mysqli_connect_errno())	{		echo "无法连接数据库,请稍后重试。";		exit;	}			$query = "insert into guahao values			('".$pname."', '".$psex."', '".$page."', '".$room."')";			$result = $db->query($query);	if (!$result)	{		echo $db->error;		echo"无法登陆!";		exit;	}	else	{		echo"<p>挂号成功!</p>";	}		$db->close();?><a href="guahao.html">继续挂号</a><?php} ?></body></html>

字符集问题!
1、你的表中没有给字符类型字段设置字符集(默认 latin1)
2、你在连接数据库后没有声明字符集(缺少 set names 指令)
3、你说你使用了 utf-8 字符集,而程序中有  charset=GB18030
实际是使用了gbk 字符集

GB18030 是正式的国家标准,目前尚未在计算机中实现。所以实际使用的是其子集--GBK

忽略外键:SET FOREIGN_KEY_CHECKS = 0

字符集问题!
1、你的表中没有给字符类型字段设置字符集(默认 latin1)
2、你在连接数据库后没有声明字符集(缺少 set names 指令)
3、你说你使用了 utf-8 字符集,而程序中有  charset=GB18030
实际是使用了gbk 字符集

GB18030 是正式的国家标准,目前尚未在计算机中实现。所以实际使用的是其子集--GBK
那个问题我已经解决了,就是字符集问题,谢谢斑竹大神!这么多天才来结贴

字符集问题!
1、你的表中没有给字符类型字段设置字符集(默认 latin1)
2、你在连接数据库后没有声明字符集(缺少 set names 指令)
3、你说你使用了 utf-8 字符集,而程序中有  charset=GB18030
实际是使用了gbk 字符集

GB18030 是正式的国家标准,目前尚未在计算机中实现。所以实际使用的是其子集--GBK
    ……

版主你好,我用跟楼主一样的建表命令建表,但是不能插入和楼主一样的数据,提示foreign constraints fails,请问该怎么解决呢?

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.