tags:

views:

77

answers:

5

Why wont this code work? I want to check if the users are already friends before I add.

function addFriend() {

global $userid, $friendid;

$check = mysql_query("SELECT * FROM friends WHERE userid = $userid AND friendid = $friendid");

if (mysql_num_rows($check) == 1) {
 exit("Youre already friend with this user");
} else {

$sql = "INSERT INTO friends (userid, friendid) VALUES ($userid, $friendid)";
mysql_query($sql);

if ($sql)
    echo "Success";
else 
    echo "Failure";
}
}
+1  A: 

This may not answer your question but $sql is never going to be false since you set it 3 lines above.

You may want to change mysql_num_rows($check) == 1 to mysql_num_rows($check) >= 1 incase your database does not have any unique constrants on the field pairs.

Mike B
A: 

Change:

$sql = "INSERT INTO friends (userid, friendid) VALUES ($userid, $friendid)";
mysql_query($sql);
if ($sql)
  echo "Success";
else 
  echo "Failure";
}

to:

$sql = "INSERT INTO friends (userid, friendid) VALUES ($userid, $friendid)";
mysql_query($sql);
if (mysql_affected_rows()) {
  echo "Success";
else 
  echo "Failure";
}

See mysql_affected_rows().

Your first version will always return success since you're testing that $sql is empty or not and it isn't because you've just assigned a non-empty value to it (being the SQL for the query).

cletus
A: 

fixed it

didnt have any auto_increcement in friends table

Makan
A: 

Hello,

Did you try including the reverse situation in your query too? I believe the friend table denotes who is friends with who in the order of the request. So if I request you as a friend, I would be the user, but if you requested me, I would be the friend ID. So you also need to check where the userid = $friendid and friendid = $userid.

Might that be it? Hard to tell from your question what exactly is the issue.

NOTE: I am not a PHP expert, so my response is strictly to the Facebook API and not PHP itself. Just stating before I may possibly get my answer demoted :-)

Brian
A: 

Like Mike B said above, $sql will never be false because you set it to the query. You need to set the result of the query to a variable and then test that:

$result = mysql_query($sql);
if ($result)
    echo "Success";
else 
    echo "Failure";
}
NerdStarGamer