AND
is a logical operator that returns true iff all its arguments are true. If you're talking about having more than one column in a result, simply separate them by commas:
SELECT COUNT(id), power
FROM table
WHERE ...
However, if power
isn't functionally dependent on id
and there are more than one row with a given id
, you could get any of the power
values (on DBMSs other than MySQL, you'd need to GROUP BY
power for the query to even work).
Instead of enforcing uniqueness in PHP, declare a UNIQUE
index on column username. Column id
should be a primary key, which implies that it's unique.
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(64) UNIQUE NOT NULL,
...
);
Or, if the table already exists,
CREATE UNIQUE INDEX username ON users (username);
Off Topic
By calling UPPER
on column username, you're preventing any index from being used, causing MySQL to have to scan the entire table to execute the query. If you want your user names to be case insensitive, convert them before storing them. This is easily accomplished with triggers, which you can read about in the MySQL reference manual.
delimiter ;;
CREATE TRIGGER upcase_username_insert
BEFORE INSERT
ON TABLE users
FOR EACH ROW
NEW.username=UPPER(NEW.username)
END;;
CREATE TRIGGER upcase_username_update
BEFORE UPDATE
ON TABLE users
FOR EACH ROW
NEW.username=UPPER(NEW.username)
END;;
delimiter ;
While using sprintf
to combine strings will work fine, it's not standard practice. Variables are interpolated into double quoted strings, so you can simply write "SELECT ... WHERE "
.
Make sure you're storing hashed and salted passwords (using a cryptographically secure hash, which MD5 isn't, these days) rather than plain passwords.
Finally, but most importantly, depending where the values interpolated into the query come from and what other processing is done on them, your query could be vulnerable to SQL injection. Use PDO and prepared statements instead (prepared statement parameters are invulnerable to SQL injection). Read "Writing MySQL Scripts with PHP and PDO" for a PDO tutorial.