MSU_Bulldog MSU_Bulldog - 7 months ago 22
PHP Question

PHP: not saving apostrophe

I have a php page that saves some data to my database. It works with all strings with special characters (. , ? !) but it doesn't work with apostrophes (').

This is my php:

$message = trim(strip_tags($_REQUEST['message']));
$safe_variable = mysqli::escape_string($message);

$i_sql = "INSERT INTO tableName ( id_user, username, message) VALUES ( '".$id_user."', '".$username."', '".$safe_variable."')";
$i_res = mssql_query($i_sql);


I've tried with and without this line:

$safe_variable = mysqli::escape_string($message);


And I've read that I should use
mysql_real_escape_string
but that it is no longer supported and I should use
mysqli::escape_string
instead.

What am I doing wrong in my PHP or what should I be using to be able to save apostrophes?

Note:

$message
is
I'm
when I test.

Answer

escape_string() cannot be called statically with mysqli::escape_string($message)

Furthermore mssql_query($i_sql); doesn't make any sense here as it looks like your're using mysql as db.

The code can be fixed like this:

// This is the object that represent the connection to the db
$conn = new mysqli( 'localhost', 'user', 'password', 'db_name');

$message = trim(strip_tags($_REQUEST['message']));
$safe_variable = $conn->escape_string($message); // fixed here

$i_sql = "INSERT INTO tableName ( id_user, username, message) VALUES ( '".$id_user."', '".$username."', '".$safe_variable."')";
$i_res = $conn->query($i_sql); // fixed here

The above, of course, assuming you're using mysql as database.

Anyway I would strongly suggest to use prepared statements instead of escaping strings.