I have an application to add friends. I need to have my script to check, if the users’ already friends. I thought I could do this by a COUNT. I did like this:
$username = $_GET[user];
$ven_til_id = $_SESSION['userID'];
$num = 1;
if(isset($_GET['add_friend'])){
$check=("SELECT username,ven_til_id, COUNT(*) AS num FROM friends WHERE username=$username AND ven_til_id=$ven_til_id GROUP BY username,ven_til_id")or die(mysql_error());
$result=mysql_query($check);
if(!$result){
echo "Cant run query.";
} else {
$num = mysql_num_rows($result);
}
if($num>0){
header("Location: /profil/$username?add_error");
} else {
$sql=mysql_query("INSERT INTO friends (username,ven_til_id)VALUES('$username', '$ven_til_id')")or die(mysql_error());
header("Location: /profil/$username");
}
}
?>
But when I’m adding one friend it’s fine. It adds it and everything is fine. But then when I try to add another, it says we’re already friends. I guess it’s because it’s counting how many times my ID (ven_til_id) is listed in the tables.
You’re missing a comma:
should be
Also, your reference to the count field is incorrect – it should be the third column or
$row[2]You may want to make your code more robust by referring to fields by name eg
$row['num']One final thing to confirm is that the value being retrieved with a count is being treated as an integer not a string. I don’t think it’s the problem here but you may want to explicitly cast it to avoid possible issues later eg…
Option 1
Just select the appropriate rows and see how many records you get back…
Then just count the number of records returned using PHP – eg
mysql_num_rows()(I think that’s the correct function name)Clarification:
Change
to
Option 2
Get MySQL to do the counting for you – in qhich case you need to tell it to group multiple record together…
Then just read the 3rd value of the first row (
num) and you’ll have a countNB: The second method may be overkill if you’re only ever expecting a 1 or a 0