简体   繁体   中英

what's wrong with this sql query?

Okay I have two variables in PHP

$username;
$password;

which are initialized to the data retrieved from $_POST variable :)

I have this SQL query

$sql = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . $password . "')";

But this doesn't works and returns me nothing :(

Can you instruct me into the right direction. Please?

查询在结尾处有一个右括号,没有任何理由,它将无法工作。

What's wrong with it?

Everything, unfortunately. In particular it's open to SQL injection attacks.

If that's a verbatim cut&paste, then the reason it's not actually working is a trailing closing bracket. Presumably you're not checking for errors when you call this?

Using the base MySQL API it should be:

$sth = $db->prepare("SELECT COUNT(*) FROM users WHERE username = ? AND password = ?");
$sth->execute($username, $password);
list($count) = $sth->fetchrow();
$authorized = ($count > 0);

or similar (code untested, E&OE, etc...)

eeek! sql injection for one!

EDIT: What's your favorite "programmer" cartoon?

Why is there a stray ) at the end of your query? It shouldn't be there.

Oh, and thirded on SQL injection. BAD.

You seem to have an excess closing parenthesis at the end of your query string.

[Edit] - for those screaming SQL injection attacks: we don't know what the user has done with their variables before using them in the query. How about benefit of doubt? ;-)

First of all, never, ever do it like this. Please read about SQL injection and don't write any SQL until you have understood what it says. Sorry, but this is really essential.

That said, your query contains a closing bracket. That looks like a syntax error. Do you get an error executing it?

There's an extra parenthesis on the right hand side of the query.

Also, if you do not sanitize your code properly you're going to be vulnerable to SQL injection. You should really be using parameterized queries, but in lieu of that at least use mysql_real_escape_string() on $username and $password .

Also, as a bit of ghost debugging, it's very possible that your passwords are MD5 hashed in the database, since you should never store them in plain text.

Try:

$username = mysql_real_escape_string($_POST["username"]);
$password = md5($_POST["password"]);

$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";

In addition to all the other problems noted. The Password in the Users table is stored encrypted. Unless you've run the Password through the MySQL password encryptor, you will never see any data from this query as the passwords won't match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM