slashes confusion with php

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.
hibbsusanAsked:
Who is Participating?
 
hibbsusanConnect With a Mentor Author Commented:
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
 
KalpanCommented:
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
 
Amar BardoliwalaCommented:
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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Loganathan NatarajanLAMP DeveloperCommented:
Please try with mysql_real_escape_string() ...
0
 
Lee SavidgeCommented:
When sending data to a database with apostrophes you should replace one apostrophe with two
0
 
Marco GasiFreelancerCommented:
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
 
liveaspankajCommented:
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
 
Ray PaseurCommented:
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
 
hibbsusanAuthor Commented:
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
 
liveaspankajCommented:
try does the mysql_real_escape_string add anything?

you can try

stripslashes(str_replace("'", "''", $row['company_name']));
0
 
Ray PaseurCommented:
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
 
hibbsusanAuthor Commented:
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
 
liveaspankajCommented:
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
 
hibbsusanAuthor Commented:
i don't understand why i need to replace single quotes. single quotes aren't a problem..

Can you explain?

Thanks!
0
 
hibbsusanAuthor Commented:
I'm so sorry, that post made no sense at all. total lack of sleep.
0
 
hibbsusanAuthor Commented:
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
 
liveaspankajCommented:
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
 
hibbsusanAuthor Commented:
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
 
liveaspankajCommented:
remove mysql real escape string
and addslasses and str_replace

when you pull data
you might need to stripslasses
0
 
hibbsusanAuthor Commented:

and addslasses and str_replace

do you mean "and addslasses and str_replace" ?
0
 
Ray PaseurCommented:
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
 
liveaspankajCommented:
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
 
Ray PaseurCommented:
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
 
hibbsusanAuthor Commented:
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
 
liveaspankajCommented:
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
 
hibbsusanAuthor Commented:
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
 
liveaspankajCommented:

this query has no data so no problem of mysql escape of addslasses or anything
0
 
hibbsusanAuthor Commented:
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
 
liveaspankajCommented:
can you do something to show a real query?
0
 
liveaspankajCommented:

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
 
hibbsusanAuthor Commented:
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
 
liveaspankajCommented:
$attn   = str_replace("'", "''", addslashes($_POST['attn']));
0
 
liveaspankajCommented:
ok congrats
0
 
hibbsusanAuthor Commented:
seems to work. though it seems a bit obscure..

any reasons it oughtn't to be used?

Thanks for all the help!!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.