user1846761
user1846761

Reputation: 61

How can i store a string with quotes in it into a sql db?

I have a site and the user inputs a title. I want the title to be able to use any punctuation. My problem is ill have a query:

"INSERT INTO table(title, body) VALUES ('$title','$body')";

where $title and $body are GET vars. What happens it when i put a quote in for the title it acts as if it ends the string and creates and invalid sql query. Say i have

$title = "I'm entering a title";
"INSERT INTO table(title, body) VALUES ('$title','$body')";
//"INSERT INTO table(title, body) VALUES ('I'm entering a title','$body')";

It ends the string. I've tried using all double quotes and escape characters but nothing. Does anyone know a solution?

Upvotes: 1

Views: 2555

Answers (6)

zorro
zorro

Reputation: 3

You need to mysqli_real_escape_string your SQL.

Upvotes: 0

Naz
Naz

Reputation: 2775

There is already a built-in method for this situation... have a look in mysql_escape_string method... see the below code...

$title = "I'm entering a title";
$title = mysql_escape_string( $title );
// $title === I\'m entering a title
"INSERT INTO table(title, body) VALUES ('$title','$body')";
// "INSERT INTO table(title, body) VALUES ('I\'m entering a title','$body')";

Upvotes: 0

Basith
Basith

Reputation: 1075

You can try this php function..

mysql_real_escape_string

    $title1       = "I'm entering a title";
    $title        = mysqli_real_escape_string($title1);
    "INSERT INTO table(title, body) VALUES ('$title','$body')";

Try with this, hope this ll help you...

Upvotes: 0

Sohail Ahmed
Sohail Ahmed

Reputation: 1667

Use these two functions while entring data to database and out from database.

/****************************************/
/* Encode special chars                 */
/*                                      */
/****************************************/

function DBin($string) 
{
    return  trim(htmlspecialchars($string,ENT_QUOTES));
}

/****************************************/
/* Decode special chars                 */
/*                                      */
/****************************************/

function DBout($string) 
{
    $string = trim($string);
    return htmlspecialchars_decode($string,ENT_QUOTES);
}

Upvotes: 1

Marco Berrocal
Marco Berrocal

Reputation: 362

You should sanitize your variables via PHP first and then send them clean via PDO or MySQLi...

Upvotes: 0

John Woo
John Woo

Reputation: 263723

Your query is vulnerable with SQL Injection but using PHP's PDO or MySQLi helps you solve that problem (also allows you to insert single quotes in the database), Please read the article below

Upvotes: 1

Related Questions