如何向有外键约束的字表中插入记录?
我在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,请问该怎么解决呢?

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.
