j.gooch
j.gooch

Reputation: 305

How would you enter special characters into MySQL from PHP?

Effectively, what I am attempting to do is enter a string similar to this string into MySQL (it's one line, made into two for readability)

fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;
stroke-linecap:butt;stroke-  linejoin:miter;stroke-opacity:1

MySQL allows me to INSERT the string into the field using phpMyAdmin and phpMyAdmin adds the field as (again one line, made into two for readability):

('fill:#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-
linecap:butt;stroke-linejoin:miter;stroke-opacity:1'' in ''field list')

With my PHP code I attempted to add the in field list part to my code as follows

$rectangle_array[$rstyle] = $rectangle_array[$rstyle] . "' in ''field list'";
$mysql_rectangle_table_entry = "INSERT INTO $mysql_table VALUES
                               ($rectangle_array[$rstyle], 'rect',
                               $rectangle_array[$rid], $rectangle_array[$rwidth],
                               $rectangle_array[$rheight], $rectangle_array[$rx],
                               $rectangle_array[$ry])";
$run = mysql_query($mysql_rectangle_table_entry) or die(mysql_error());

And upon running the code I receive the following error.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':#0000ff;fill-rule:evenodd;stroke:#000000;stroke-width:1px;stroke-linecap:butt;s' at line 1

What can I do to make this work?

Upvotes: 0

Views: 2654

Answers (2)

Jason McCreary
Jason McCreary

Reputation: 72961

As noted in the comments…

You could use mysql_real_escape_string() to escape any MySQL special characters before insertion.

For example:

$sql = "INSERT INTO my_table (string_column) VALUES ('" . mysql_real_escape_string($string) .  "')";

Another option is to use Prepared Statements with PHP's MySQLi or PDO.

Upvotes: 2

Jérémie Parker
Jérémie Parker

Reputation: 3174

You might want to have a look either at prepared statements or mysql_real_escape_string to escape special characters that might break your INSERT.

Upvotes: 1

Related Questions