I'm saving queries in my DB as strings
here's my code:

$SQLcode="SELECT *	
FROM ...
WHERE field="blah blah"
HAVING field2<$x";


$query = "INSERT INTO tblQ (qId, qName, description, SQLcode) VALUES (NULL, '$qName', '$description', '$SQLcode');";

the problem is inserting a string into the $SQLcode, if I do it this way:
$SQLcode= " SELECT * FROM ...WHERE field=' blah blah ' HAVING field2<$x ";
it makes problem with the $query cuz there are ' around the $SQLcode:
$query = "INSERT INTO tblQ (qId, qName, description, SQLcode) VALUES (NULL, '$qName', '$description', '$SQLcode');";

if I do it like this:
$SQLcode='SELECT * FROM ...WHERE field="blah blah" HAVING field2<$x';
then the $x is saved as "$x" and not as the value in it..

is there a way around this craziness? gotta be..!

Dani AI

Generated

ran into the usual PHP quoting/interpolation snag and gave the quick fix: double-quoted strings or concatenation will expand a variable, single-quoted strings will not. That answers the immediate symptom (why "$x" is stored instead of the value), but it is brittle and can lead to messy quoting and security issues if values are injected directly into SQL.

A more robust pattern is to store SQL templates with placeholders and bind values at execution time (prepared statements). Retrieve the template from the DB, prepare it with PDO or mysqli, then bind/execute with the actual values. This removes the need to wrestle with single vs double quotes and prevents SQL injection when done correctly.

$stmt = $pdo->prepare($template_from_db);
$stmt->execute([':param' => $value]);
$rows = $stmt->fetchAll();

See the PHP docs on PDO prepared statements for details. If prepared statements are not possible, use the API escape functions (for example, mysqli_real_escape_string or PDO::quote) — but escaping is error-prone compared with bound parameters. To store raw SQL in PHP source without interpolation consider nowdoc/heredoc; see PHP string syntax.

Finally, avoid executing arbitrary templates pulled from the database without validation. Treat stored SQL as code: restrict templates to trusted patterns, prefer placeholders, and follow the for secure handling.

Recommended Answers

All 3 Replies

You need double quotes, otherwise $x won't be processed. An alternative is this:

'SELECT * FROM ...WHERE field="blah blah" HAVING field2<'.$x

but OF COURSE!!! thank you!

You're welcome :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.