xRobot
xRobot

Reputation: 26567

How to add values with a comma?

I need to insert values like this: 'aaaa, bbbb' in the database.

I am using this query:

INSERT INTO a (title) VALUES ('aaaa, bbbb');

but in the database is saved only aaaa. Why ?

This is the script:

   $a = 'aaaa, bbbb';
   $query = "INSERT INTO test (title) VALUES ('".$a."');";
   $res = mysqli_query($db_con, $query) or die("fail: " . $query . ' Error:' . mysqli_error());

Upvotes: 2

Views: 97

Answers (2)

vp_arth
vp_arth

Reputation: 14982

There is nothing wrong in your SQL.

I make SQLFiddle to demonstrate that:

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

Double-check you environment: how you fetch values, have you some related triggers etc.


Correct way to make queries like this, is using prepared statements:

$query = "INSERT INTO a (title) VALUES (?)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $a);
$stmt->execute();

Or, procedural style:

$query = "INSERT INTO a (title) VALUES (?)";
$stmt = mysqli_prepare($db_con, $query);
mysqli_stmt_bind_param($db_con, "s", $a);
mysqli_stmt_execute($stmt);

Upvotes: 4

ComputerLocus
ComputerLocus

Reputation: 3618

Works fine for me:

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)

Upvotes: 3

Related Questions