我需要插入这样的值:' aaaa,bbbb'在数据库中。
我正在使用此查询:
INSERT INTO a (title) VALUES ('aaaa, bbbb');
但在数据库中只保存了aaaa。 为什么?
这是剧本:
$a = 'aaaa, bbbb';
$query = "INSERT INTO test (title) VALUES ('".$a."');";
$res = mysqli_query($db_con, $query) or die("fail: " . $query . ' Error:' . mysqli_error());
答案 0 :(得分:4)
您的SQL没有任何问题。
我让SQLFiddle证明:
CREATE TABLE t (
id int primary key auto_increment,
title varchar(100)
);
INSERT INTO t (title) VALUES('aaaaa, bbbbb'), ('ccccc, ddddd');
SELECT * FROM t;
id title
1 aaaaa, bbbbb
2 ccccc, ddddd
仔细检查你的环境:你如何获取值,让你有一些相关的触发器等。
正确使用这样的查询的方法是使用预准备语句:
$query = "INSERT INTO a (title) VALUES (?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $a);
$stmt->execute();
或者,程序风格:
$query = "INSERT INTO a (title) VALUES (?)";
$stmt = mysqli_prepare($db_con, $query);
mysqli_stmt_bind_param($db_con, "s", $a);
mysqli_stmt_execute($stmt);
答案 1 :(得分:3)
对我来说很好:
mysql> create table xrobot_test (
-> title varchar(100)
-> );
Query OK, 0 rows affected (0.01 sec)
mysql> describe xrobot_test;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| title | varchar(100) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
1 row in set (0.00 sec)
mysql> INSERT INTO xrobot_test (title) VALUES ('aaaa, bbbb');
Query OK, 1 row affected (0.00 sec)
mysql> select * from xrobot_test;
+------------+
| title |
+------------+
| aaaa, bbbb |
+------------+
1 row in set (0.00 sec)