Problem with mysql_fetch_assoc


I am trying to query the database to see if the username that someone requests is already taken by another user. My code looks like this:

else if ($_POST) { // if someone has submited a POST form, this will be true
$link = mysql_connect("localhost","businessinme","bua645");

$query = "SELECT COUNT (*) as numUsers FROM users WHERE
$res = mysql_query($query);
if (!$res) {
die("MySQL error happened with query: $query error: ".mysql_error());

$row = mysql_fetch_assoc($res);
if ($row[‘numUsers’] > 0) {
print ‘The username you specified has already been registered by another member.

.‘Please hit the back button and choose a different username.!’;

When I try to run this bit I keep getting the following error message:

MySQL error happened with query: SELECT COUNT () as numUsers FROM users WHERE username='dsm error: You have an error in your SQL syntax near '() as numUsers FROM users WHERE username=‘dsm’ at line 1

Could someone let me know where I’m going wrong. Thanks


echo out your sql statement. I bet you forgot to close your single quote around user name.

Relevant line of code:
$query = “SELECT COUNT (*) as numUsers FROM users WHERE

Should be (note I used single rather then double quotes):
$query = ‘SELECT COUNT (*) as numUsers FROM users WHERE
username=’’ . $_POST[‘username’] . ‘’’ ; <-- note the close quote


You should at least add mysql_escape_string around your queries, what you have now is VERY insecure.