user918477
user918477

Reputation:

insert special character in mysql using php

When, I am trying to insert "I am Fine & How are you". And, when i look back to the database, then i see, only "I am Fine" is inserted rest words are trimmed from that sentence. This problem also arise, when i use ' in between the sentence.

My sample code is

$title= mysql_real_escape_string($_POST['title']);
mysql_query("insert into table_db(TITLE) values ('".$title."')") or die(mysql_error());

I searched on google, and found many solution, but, my problem still unsolved. help will be appreciated !!

varchar(300)

Upvotes: 1

Views: 3185

Answers (3)

SagarPPanchal
SagarPPanchal

Reputation: 10131

try

mysql_query("INSERT INTO test_tbl values('$title')");

instead of

mysql_query("insert into table_db(TITLE) values ('".$title."')") or die(mysql_error());

my below code works fine

<?php 
    mysql_connect('localhost','root','');
    mysql_select_db('core');

    if(isset($_POST['submit'])){
        echo $title=mysql_real_escape_string($_POST['title']);
    mysql_query("INSERT INTO test_tbl values(null,'','','$title')");
    }
?>


<html>
    <body>
        <form method="post">
            <input type="text" name="title">
            <input type="submit" name="submit">
        </form>
    </body>
</html>

Upvotes: 0

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52157

I'm not familiar with PHP, but this kind of problem would generally be solved by using bound parameters (a.k.a. "bind variables") and letting the underlying database API worry about special characters.

By escaping and concatenating strings yourself, you are essentially betting that escape function is up-to-date relative to your database of choice, which appears not to be the case here.

Upvotes: 1

Marc B
Marc B

Reputation: 360882

You're using the proper method to make that string "safe" for the query, so it's unlikely to be the query itself causing the problem. What is the type/size of the TITLE field? If it's a char(9) or varchar(9), then that would just hold your "I am Fine" and ignore the rest.

Upvotes: 2

Related Questions