?
Solved

slashes confusion with php

Posted on 2011-11-01
34
Medium Priority
?
329 Views
Last Modified: 2012-05-12
php seems not to give a full response to an ajax request when the cell in the mysql database contains an apostrophe. It stops right at the apostrophe, only sending back what comes before it.

should I addslashes before storing the data, or stripslashes when I'm requesting it?

company_name" => stripslashes($row['company_name']),

Open in new window

?

I really have tried a lot of combinations!

Any help would be appreciated! Thank you.
0
Comment
Question by:hibbsusan
  • 13
  • 12
  • 4
  • +5
34 Comments
 
LVL 14

Expert Comment

by:Kalpan
ID: 37061327
you would need to use stripslashes for storing the data with apostrophe, since it automatically adds the / where it finds the '

http://php.net/manual/en/function.stripslashes.php

http://php.net/manual/en/function.addslashes.php
0
 
LVL 11

Expert Comment

by:Amar Bardoliwala
ID: 37061360
Hello hibbsusan,

Have you tried mysql_real_escape_string?

Following are some links that should help you.

http://php.net/manual/en/function.mysql-real-escape-string.php

http://www.webmasterworld.com/php/3210921.htm

http://www.phpbuilder.com/board/showthread.php?t=10328088

Regarding your problem,

it is not much clear where exactly you are getting problem. You might need to provide more details

1. are you getting problem while storing data in table?
2. are you getting problem while retrieving data from table?
3. are you getting problem while showing data in html page.

Hope this will help.

Thank You.

Amar.
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
ID: 37061371
Please try with mysql_real_escape_string() ...
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 25

Expert Comment

by:Lee Savidge
ID: 37061376
When sending data to a database with apostrophes you should replace one apostrophe with two
0
 
LVL 31

Expert Comment

by:Marco Gasi
ID: 37061404
I would use addslashes function (http://it2.php.net/manual/en/function.addslashes.php) inserting values in database. The classical example is here:

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

Cheers
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37061665
its not a slashes issue...

you will face the problem only with mysql queries because ' is a comment tag. so everything after ' is ignore. you need to add double '' to make it read what you want. this is done my mysql_real_escape_string() so finally your statement will be:


company_name" => stripslashes(mysql_real_escape_string($row['company_name'])),

or
company_name" => mysql_real_escape_string($row['company_name']),


anything that works for you
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37062498
Have a quick look at this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_6630-Magic-Quotes-a-bad-idea-from-day-one.html

The steps that I have found to work are these (and you may not need the first two):

1. Prepare a sturdy test case and a back up so you can revert if this causes problems.
2. Turn off "magic quotes" then run your tests to verify that everything is still OK.
3. Use mysql_real_escape_string() on every external data field that is to be inserted into any mysql query().

You must connect to a data base before you call mysql_real_escape_string() since it is context-aware.
http://php.net/manual/en/function.mysql-real-escape-string.php

HTH, ~Ray
0
 

Author Comment

by:hibbsusan
ID: 37062962
Thanks for all the help,

the problem seems like it may be in the part of the script that's passing the information from address_process.php to the original script. When I go to address_process.php, the results show apostrophes and text that comes before and after them fine.  Is something going on that the json is being decoded by jquery incorrectly?

		  $.ajax ({  
			type: "POST",
			url: "address_process.php",
			success: function(data)
			{
				
				
				$.each(data, function(key, val) {

Open in new window


Thanks again to everyone for the answers. I will continue to experiement with magic quotes and mysql_real_escape_string(). I have hadn't any luck yet with mysql_real_escape_string() however
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37062989
try does the mysql_real_escape_string add anything?

you can try

stripslashes(str_replace("'", "''", $row['company_name']));
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37063357
One technique that I have found useful when dealing with background scripts or other asynchronous scripts (where browser output is not readily available) is to do something like this...

ob_start();
echo "Any message you need here";
var_dump($any_data_like_$_POST);
$msg = ob_get_clean();
mail ('You@Your.org', 'MSG FROM THE BACKGROUND', $msg);
0
 

Author Comment

by:hibbsusan
ID: 37100519
I am very sorry to all the contributors for being absent from this post for so long. but it was necessary as i was in a bit over my head at that time.

However, I'm a bit clearer on php/ajax/jquery/mysql now. Though I still do have this problem.

When the data is going into the database, I am using the mysql_real_escape_string():

$id_user        = mysql_real_escape_string($_SESSION['id_user']);
$attn           = mysql_real_escape_string($_POST['attn']);
$company_name   = mysql_real_escape_string($_POST['company_name']);
$address_line_1 = mysql_real_escape_string($_POST['address_line_1']);
$address_line_2 = mysql_real_escape_string($_POST['address_line_2']);
$city           = mysql_real_escape_string($_POST['city']);
$state          = mysql_real_escape_string($_POST['state']);
$zip            = mysql_real_escape_string($_POST['zip']);
$phone          = mysql_real_escape_string($_POST['phone']);
$time           = mysql_real_escape_string($_POST['added_time_stamp']);

Open in new window


I have also tried using addslashes() here and stripslashes() when I pull it back out. Each time the string is truncated at the first apostrophe.

Any ideas? Should I use mysql_real_escape_string() on both putting in and pulling out? Or mysql_real_escape_string() on putting into DB and stripslashes when pulling out? I feel like I have tried about every permutation of these functions :(

Thank you all again!

0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37100555
did you try adding this part apart from addslasses. This is more important than slasses because your problem is not slasses related:

str_replace("'", "''", $row['company_name'])
0
 

Author Comment

by:hibbsusan
ID: 37100581
i don't understand why i need to replace single quotes. single quotes aren't a problem..

Can you explain?

Thanks!
0
 

Author Comment

by:hibbsusan
ID: 37100602
I'm so sorry, that post made no sense at all. total lack of sleep.
0
 

Author Comment

by:hibbsusan
ID: 37100609
but i do wonder how i will know which double-quotes were entered by the user, and which were put there by the str_replace function (?)
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37100866
1. the apostrophe you mentioned is single-quote i guess. so that is entire problem. because its a comment sign for mysql.

2. we are replacing single quote with two single quote and not a double quote :) though it will look like. So when you read from mysql you will get it alright, without a need to do anything.

0
 

Author Comment

by:hibbsusan
ID: 37100973
should i do this in addition to mysql_real_escape_string, instead of it, before or after?

do I need to do something when i pull the data out of the DB?

Thank you
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37101375
remove mysql real escape string
and addslasses and str_replace

when you pull data
you might need to stripslasses
0
 

Author Comment

by:hibbsusan
ID: 37101457

and addslasses and str_replace

do you mean "and addslasses and str_replace" ?
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37101471
Please read this article.  It will explain some of what is going on here.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_6630-Magic-Quotes-a-bad-idea-from-day-one.html

Your strategy should almost certainly be this:  When you receive external data in the PHP script, use stripslashes() to remove any externally injected slashes like those that might come from magic quotes.  Next, prepare the data for use in a query by using mysql-real-escape_string() only once.  Forget about addslashes().  

Check your data base and see if you have unwanted slashes in the data.  It could have gotten there if you used addslashes() in combination with mysql_real_escape_string() or if you used addslashes() or mysql_real-escape_string() in an environment that had magic quotes turned on.  If so, you might consider putting stripslashes() into the data recovery process, or correcting the data.
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37101524
yes add slashes

and if it creates doubles slashes that mean magic quotes is on. so you can omit adding slashes.

so
addslashes(str_replace("'", "''", $row['company_name']));
or
str_replace("'", "''", $row['company_name']);


before everything else..i would ask you to check if you are using mysql_real_escape_string before connting to mysql or after connection. if you are using before connection. you can try connection before that, and you might not need to worry about str_replace and addslashes...and mysql_real_escape_string might do its job
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37101601
if it creates doubles slashes that mean magic quotes is on

You could run this script.  It might be faster.
<?php if (ini_get('magic_quotes_gpc')) echo "MAGIC QUOTES IS ON";

Open in new window

0
 

Author Comment

by:hibbsusan
ID: 37101654
I believe that that is basically what I am doing. And I can see here that I have magic quotes turned off.


Putting info into the DB
$id_user        = $_SESSION['id_user'];
$attn           = $_POST['attn'];
$company_name   = $_POST['company_name'];
$address_line_1 = $_POST['address_line_1'];
$address_line_2 = $_POST['address_line_2'];
$city           = $_POST['city'];
$state          = $_POST['state'];
$zip            = $_POST['zip'];
$phone          = $_POST['phone'];
$time           = $_POST['added_time_stamp'];

$clean_id_user          = mysql_real_escape_string ($id_user) ;
$clean_attn             = mysql_real_escape_string ($attn);
$clean_company_name     = mysql_real_escape_string ($company_name) ;
$clean_address_line_1   = mysql_real_escape_string ($address_line_1) ;
$clean_address_line_2   = mysql_real_escape_string ($address_line_2) ;
$clean_city             = mysql_real_escape_string ($city) ;
$clean_state            = mysql_real_escape_string ($state) ;
$clean_zip              = mysql_real_escape_string ($zip) ;
$clean_phone            = mysql_real_escape_string ($phone) ;
$clean_time             = mysql_real_escape_string ($time) ;




$sql="INSERT INTO billing_address (id, attn, company_name, address_line_1, address_line_2, city, state, zip, phone, added_time_stamp)
VALUES ('$clean_id_user', '$clean_attn ','$clean_company_name','$clean_address_line_1','$clean_address_line_2','$clean_city','$clean_state','$clean_zip','$clean_phone', '$clean_time')";


if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
//echo "1 record added";

mysql_close($con);

Open in new window


Requesting info from the DB
if (!$result)
{
	die(mysql_error());
	}
	else
	{ 
	$arr = array(); // create an empty array
	while ($row = mysql_fetch_array($result)) 
	{
	
	$arr[] = array( 
	"attn" => stripslashes($row['attn']), 
	"company_name" => stripslashes($row['company_name']),
	"address_line_1" => stripslashes($row['address_line_1']),
	"address_line_2" => stripslashes($row['address_line_2']),
	"city" => stripslashes($row['city']),
	"state" => stripslashes($row['state']), 
	"zip" => stripslashes($row['zip']), 
	"phone" => stripslashes($row['phone']), 
	); // push all object inside the array
	
	}
	header("Content-type: application/json"); // set the header, it's safe
	echo json_encode($arr); // encode the full object to a json string object

}
mysql_close($con);

Open in new window



Putting requested data back on the page
	$(document).ready(function() {
		$("#see_frequent_addresses").click(function()
		{		
		/* prevent from appending same addresses more than once if button has already been clicked */
		
			 
		
		
		  $.ajax ({  
			type: "POST",
			url: "address_process.php",
			success: function(data)
			{
				
				
				$.each(data, function(key, val) {
					var aS = "";
				$("#addresses").append("<input type='button' id='new_address'  value='add new address' />");
				
				 aS = "<div id='address_container_"+(key+1)+"' class='address_container'>";
							aS += 		"<div>";
							
							
							aS += 			"<div id='attn_"+(key+1)+"' class='address_label'>attn";
							aS += 				"<input type='text'  class='address_text' id='text_attn_"+(key+1)+"'  disabled='disabled' value='"+val.attn+"' />";
							aS +=			"</div>";
							
							
							aS +=			"<div id='company_name_"+(key+1)+"' class='address_label'>company name";
							aS +=					"<input type='text' class='address_text' id='text_company_name_"+(key+1)+"'  disabled='disabled' value='"+val.company_name+"' />";
							aS +=			"</div>";
							
							
							
							aS +=			"<div id='address_line_1_"+(key+1)+"' class='address_label'>address line 1";
							aS +=				"<input type='text'  class='address_text' id='text_address_line_1_"+(key+1)+"'  disabled='disabled' value='"+val.address_line_1+"'/>";
							aS +=			"</div>";
							
							
							aS +=			"<div id='address_line_2_"+(key+1)+"' class='address_label'>address line 2";
							aS +=				"<input type='text'  class='address_text' id='text_address_line_2_"+(key+1)+"'  disabled='disabled' value='"+val.address_line_2+"'/>";
							aS +=			"</div>";
							
							
							aS +=			"<div id='city_"+(key+1)+"' class='address_label'>city";
							aS +=				"<input type='text'  class='address_text' id='text_city_"+(key+1)+"'  disabled='disabled' value='"+val.city+"' />";
							aS +=			"</div>";
							
							
							aS +=			"<div id='state_"+(key+1)+"' class='address_label address_float_label'>state";
							aS +=			"</div>";
							
							
							aS +=			"<div id='zip_"+(key+1)+"' class='address_label address_float_label'>zip";
							aS +=			"</div>";
							
							aS +=			"<div  style='clear:both' ></div>";
							
							
							
							aS +=			"<input type='text'  class='address_text address_float' id='text_state1_"+(key+1)+"'  disabled='disabled' value='"+val.state+"' />";
							
							aS +=			"<input type='text'  class='address_text address_float' id='text_zip_"+(key+1)+"'  disabled='disabled' value='"+val.zip+"' />";
							
							aS +=			"<div style='clear:both' ></div>";
							
							
							aS +=			"<div id='phone_"+(key+1)+"' class='address_label'>phone";
							aS +=				"<input type='text'  class='address_text' id='text_phone_"+(key+1)+"'  disabled='disabled' value='"+val.phone+"' />";
							aS +=			"</div>";
							
										
							aS +=		"</div>";	
							
									
							aS +=		"<div id='address_buttons_"+(key+1)+"'>";	
							
							aS +=		"<a href='#' class='edit' id='"+(key+1)+"' class='address_label'>edit</a> &nbsp;<a href='#'>remove from list</a>";
							
							
							aS +=		"</div>";		
							aS +=	"</div>";		
				
						
					$("#addresses").append(aS);
					
					$("#addresses input[type=text]").css({'outline': 'none', 'border': '2px solid #91D9F8'});
					})
				}
			});
		});
	});

Open in new window



Have I followed your instructions correctly?
Thank you
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37101692
did you try the other option?

can you echo $sql; and show what the query looks like.

can you also tell if you are getting any mysql error?
0
 

Author Comment

by:hibbsusan
ID: 37101796
this is $sql when putting data into db

INSERT INTO billing_address (id, attn, company_name, address_line_1, address_line_2, city, state, zip, phone, added_time_stamp) VALUES ('7', ' ','','','','','','','', '')

without anything posted of course. just the user id from a $_SESSION
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37101855

this query has no data so no problem of mysql escape of addslasses or anything
0
 

Author Comment

by:hibbsusan
ID: 37101868
the query has no data because it's just a copy of the query without anything posted to it. When I submit the form on the other page, the ajax puts values into it..
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37101968
can you do something to show a real query?
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37101976

did you try the other option?


did you try the other option?


did you try the other option?


did you try the other option?

0
 

Author Comment

by:hibbsusan
ID: 37110131
all right. I'm trying this:

when I put the data in the DB

$attn   = str_replace("'", "''", addslashed($_POST['attn']));

Open in new window


This is the format you mean?
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37110269
$attn   = str_replace("'", "''", addslashes($_POST['attn']));
0
 

Accepted Solution

by:
hibbsusan earned 0 total points
ID: 37110462
I ended up using :
$attn = htmlspecialchars($attn, ENT_QUOTES);

Open in new window

to put into the DB


and:
htmlspecialchars_decode($row['attn'])

Open in new window

to pull out.

It really seems to work.
0
 
LVL 5

Expert Comment

by:liveaspankaj
ID: 37110508
ok congrats
0
 

Author Closing Comment

by:hibbsusan
ID: 37163640
seems to work. though it seems a bit obscure..

any reasons it oughtn't to be used?

Thanks for all the help!!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
It’s a season to be thankful, and we’re thankful for users like you who engage on site, solve technology problems, and network with others in the industry. What tech are we most thankful for? Keep reading.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
Suggested Courses
Course of the Month14 days, 15 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question