red23jordan
red23jordan

Reputation: 2891

Add data into php mysql with single quotes

This is my code:

$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");

      while($e=mysql_fetch_assoc($q))

              //$output[]=$e;
              //echo $e['NAME'];
              {
              $name = $e['NAME'];
              $brand = $e['BRAND'];
              $category = $e['CATEGORY'];
              $query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
              $result = mysql_query($query) or die("Unable to insert because : " . mysql_error()); 
              }

Since in "BRAND", there may be some data like "First's Choice".
In this case, I cannot insert to database due to error.
How can I insert data that contain single quotes? Thx

Upvotes: 1

Views: 3361

Answers (6)

Ramaraju.d
Ramaraju.d

Reputation: 1353

I was pulling my hair to solve this, finally i am ok with this solution. Try this

Upvotes: 0

Ryan
Ryan

Reputation: 433

There are two ways of accomplishing that. You can first run an escape string on it:

$newbrand = mysql_real_escape_string($brand);

and insert $newbrand. When you call it, you have to do strpslashes($newbrand);

OR you could do:

$search = array("'");
$newbrand = str_replace($search,'',$brand);

Upvotes: 1

Khurram Ijaz
Khurram Ijaz

Reputation: 1864

Try below code 

$q=mysql_query("SELECT * FROM `table1` WHERE name like '%$searchText%'");

      while($e=mysql_fetch_assoc($q))

              //$output[]=$e;
              //echo $e['NAME'];
              {
              $name = $e['NAME'];
              $brand = mysql_real_escape_string($e['BRAND']);
              $category = $e['CATEGORY'];
              $query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";
              $result = mysql_query($query) or die("Unable to insert because : " . mysql_error()); 
              }

Upvotes: 1

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

You must use :

  • $brand = mysql_real_escape_string($brand)

See PHP Documentation.

string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )

Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. (..)

Upvotes: 1

Chirag
Chirag

Reputation: 1128

Use mysql_real_escape_string

Upvotes: 1

prodigitalson
prodigitalson

Reputation: 60413

you need to use mysql_real_escape_string on the value, which you should be doing anyway. That should properly escape your value for insertion.

$name = mysql_real_escape_string($e['NAME']);
$brand = mysql_real_escape_string($e['BRAND']);
$category = mysql_real_escape_string($e['CATEGORY']);
$query = "INSERT INTO table2 (brand, name, category) VALUES ('$brand', '$name', '$category')";

Upvotes: 3

Related Questions