How to check if result of request to DB is empty?

Chris Wright via Digitalmars-d-learn digitalmars-d-learn at
Sat Dec 12 09:18:54 PST 2015

On Sat, 12 Dec 2015 07:44:40 +0000, Suliman wrote:

>>> string query_string = (`SELECT user, password FROM otest.myusers where
>>> user LIKE ` ~ `'%` ~ request["username"].to!string ~ `%';`);
>> Don't piece queries together without escaping the dynamic parts.
>> Imagine what happens when the user enters an apostrophe in the username
>> field.
> Do you mean to wrap:
>   request["username"].to!string
> in quotes?

No. You'll end up with a query like:
SELECT user, pass FROM users WHERE user LIKE '%"suliman"%'

This will only retrieve users with "\"suliman\"" in their username. But 
then I could still register with a username of "'; DROP TABLE users; --" 
and you'd be in an unhappy place. Because that would be parsed as:

SELECT user, pass FROM users WHERE user LIKE '%"';

There are two ways of avoiding this problem (SQL injection attacks). The 
first is to manually escape all input strings. This relies on you being 
ever vigilant. It also relies on you knowing every way someone can create 
a SQL injection attack. In practice, everyone will fail at one or both of 

The more successful way is to use prepared statements. In a prepared 
statement, you write something like:

auto stmt = db.prepare("SELECT username, password FROM users where 
username = ?");
auto result = stmt.execute(request["username"].to!string);

The "?" tells the database you're going to provide a piece of data there 
later, and that data is not part of the query. So you don't have to worry 
what the user entered; it's not going to mess up the query.

More information about the Digitalmars-d-learn mailing list