Monday, 28 August 2017

php - direct double quoted text can be inserted into sql database, but single quote to double quote converted string is inserted as empty into the database?



I have a textbox where i can type double quoted words like: hello i am "steve" and i can successfully insert the string into my database after mysqli_real_escape_string







php below:



$text_data = $_POST['description']; // hello my name is "steve" 
$final_text = mysqli_real_escape_string($this->conn,$text_data);

// the above without removing double quotes can be inserted into the db


but if it is single quotes and I convert to double quotes then it cannot be inserted.

$text_data = $_POST['description']; // hello my name is 'steve'
$final_text = str_replace("'",'"',$text_data);
$final_text = mysqli_real_escape_string($this->conn,$text_data);


so my questions are:





  1. how come it works with double quotes? doesn't it needs to be removed or replaced with "/ something?


  2. if the first case: double quotes work fine, then how come the second case when converted from single to double quotes cannot be inserted into the db?




Thanks a lot in advance


Answer



A couple things..



First I would do some reading on the differences between the single quote and the double quote's behaviors. Just so going forward you have a basis for the differences between the two.




Secondly lets look at the logic of your code:



If I replace the single quotes in your code like your code suggest your statement will look like this:



"hello my name is "steve""


No lets look closly at what happens between " and steve.



"hello my name is "  steve ""



The reason your query is failing, I believe is because steve is not quoted anymore.



Using prepared statement is really your best solution to the problem.



Hope that helps



UPDATED:




$text_data = "hello my name is 'steve'"; 
$final_text = str_replace("'",'\"',$text_data);

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...