I’m having a problem with an SQL query on a php page.
I’m pretty new to php so stick with me.
I have successfully created a query to select everything, but I want to include a WHERE in the query. The trouble is that the result includes quotation marks because it is html code.
I’m sure this is simple but can anyone help… problem code below:
$result = mysql_query("SELECT * FROM myTable WHERE text = '<span class="myclass">Here is my text</span>'");
Short answer
Escape the quotation marks:
Correct answer
You are almost certainly building this query dynamically (i.e., the string
<span class=\"myclass\">Here is my text</span>is in a variable, let’s call it$searchTerm).Do not, EVER, execute SQL queries with embedded variables without escaping the variable contents first. This will not only prevent such problems, but it will also prevent SQL injection attacks against your application.
Assuming the
$searchTermvariable as mentioned above, the correct way would be:Totally correct answer
Use PHP’s PDO extension, which provides easy access to this functionality (read up on variable binding) and is also 100% secure (which
mysql_real_escape_stringis not — but the topic is way too advanced to discuss here).