Reputation: 1387
I have the below SQL for postgresql database. I use it in PHP code. the below statement cause the error:
$name = "test#123";
$query = "SELECT * FROM \"Table_name\" WHERE \"Name\" = '" . $name . "'";
$result = pg_query($query) or die('Query failed: 2.12 ' . pg_last_error());
if the statement without character #
it work fine. but with the charater #
the error encountred (unterminated quoted string at or near) . how Can i solve it ?!
Upvotes: 0
Views: 2419
Reputation: 13049
Your query is fine, however #
is legacy line comment symbol in PHP. Your query text gets truncated before it hence the unterminated quoted string. Try to escape it with a backslash.
SELECT * FROM "Table_name" WHERE "Name" = 'test\#123'
Well, not the case. Actually PHP code needs a touch - escape the double quotes.
$name = "test#123";
$query = "SELECT * FROM \"Table_name\" WHERE \"Name\" = '" . $name . "';";
$result = pg_query($query) or die('Query failed: 2.12 ' . pg_last_error());
Please note that the code above is SQL injection prone. Consider using PDO and a prepared statement. Example:
$name = "test#123";
$sql_query = 'SELECT * FROM "Table_name" WHERE "Name" = :name;';
$db = new PDO(<your PDO connection string here>);
$st = $db -> prepare ($sql_query);
$result = $st -> execute([':name' => $name]) -> fetchAll();
Upvotes: 1