T
Tomasz Chmielewski
Let's assume I have this code which inserts some values into a MySQL
database:
my $var = "Jake's cake";
$SQL = "INSERT INTO `recipes` (`name`, `stat`) VALUES ('$var', 'ok')";
$my_db->do($SQL) or die "Error!\n";
Executing this will render an error:
DBD::mysql::db do failed: 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 's cake', 'ok')' at line 1 at my_script.pl line 77.
Error!
Obviously, it breaks because of an apostrophe in $var variable.
What are the ways to get around this issue?
I could prepend each apostrophe with a backslash:
$var =~ s/'/\\'/;
But I'm not sure if it's the right way to do this.
Are there any "better" approaches?
database:
my $var = "Jake's cake";
$SQL = "INSERT INTO `recipes` (`name`, `stat`) VALUES ('$var', 'ok')";
$my_db->do($SQL) or die "Error!\n";
Executing this will render an error:
DBD::mysql::db do failed: 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 's cake', 'ok')' at line 1 at my_script.pl line 77.
Error!
Obviously, it breaks because of an apostrophe in $var variable.
What are the ways to get around this issue?
I could prepend each apostrophe with a backslash:
$var =~ s/'/\\'/;
But I'm not sure if it's the right way to do this.
Are there any "better" approaches?