Add a backslash to allow single/double quotes

I have a SELECT statement,

$sql = "SELECT power_supply_id FROM power_supplies WHERE title = '".$linking_title."'";

it doesnt work, and evaluates to

SELECT power_supply_id FROM power_supplies WHERE title = 'Luke's Power Supply'

is there a way to add \ before any ’ or " in the variable?

(cause the query works if I do it by hand)

Does addslashes() do what you want?

Yes, you could addslashes to the string.
Or use a prepared statement like you know you should.



NEVER EVER put variables in your query. As mentioned, use Prepared Statements.

I would also recommend you use PDO. This tutorial will get you going.

1 Like

I prefer to enclose all plain text in single quotes and to enclose PHP variables in double quotes:

$sql = 'SELECT power_supply_id FROM power_supplies WHERE title = "' .$linking_title .'"';

Also works for src tags when used with images:

echo '<IMG src="' .$link .'" alt="' .$title .'">';

// and links

echo '<a href="' .$link .'">'  .$title .'"</a>';

Hi @John_Betong,
Correct me if I am wrong, but are you saying that you don’t use Prepared Statements?

As for your link examples, IMO, jumping in and out of the string is much more error prone and harder to read.

This is much cleaner to me…

echo "<a href='$link'>$title</a>";

It is also 35 characters VS 49. KISS

It is quite some time since I wrote any queries and use both prepared and straight SQL statements depending on complexity.

I am using a tablet at the moment and cannot test the example but hope the intermediate single quote does not add complications.

For quite some time I have used PHP Heredoc strings

Frequently have quite a few html lines within the Heredic block:

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.

  <img src="$link" alt="$title">
  <a href="$link"> $title </a>
echo $str;


Added img and link to Heredoc

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.