Got a problem that has completely stumped me... am hoping the combined wisdom of the forum could assist...

I have a php script that enables a user to follow and unfollow items on a site...

Am doing this with a table that captures basically the user's id and the item id...

The below code is what does all the dirty work...

Writing a new record to the db when a user elects to follow an item works fine... However for some reason the delete request does not want to work when a user elects to "unfollow" an item...

Would appreciate any suggestions/tips... A couple of notes, does not appear to be any issues with db connection or privilleges (have set it to full access for the user). And in any case the fact that I can write a new record for new "follows" demonstrates that db connectivity is not the issue...

THE CODE --->
  //for a user to follow a thread
    if(!empty($_POST['folVal'])){
        $fv = $_POST['folVal'];
        if($fv==1){
            //user has selected the item to be followed, so need to update UserFavourites table
            $q = "INSERT INTO tUserFavourites (ThreadID, Username ) VALUES ('{$_POST['ThreadID']}','{$_POST['Username']}')";
            $r = mysql_query($q);
            if(mysql_affected_rows() == 1) {
                //echo $fv;
                echo "true";
            } else {
            echo "false";
            }
            $r.mysql_close();
        } else 
            {
            //user has selected the item to be UNfollowed, so need to update UserFavourites table
            $q = "DELETE FROM tUserFavourites WHERE ThreadID='{$_POST['ThreadID']}' AND Username='{$_POST['Username']}'";
            $TID=$_POST['ThreadID'];
            $UID=$_POST['Username'];
            $q = "DELETE FROM tUserFavourites WHERE ThreadID='$TID' AND Username='$UID'";
           mysql_query($q);
            if(mysql_affected_rows() >0) {
                echo "true";
            } else {
            echo "false";
            }
            $r.mysql_close();
        }
    }

Dani AI

Generated

Short summary: the immediate cause reported by was the follow-flag test — the script was running the wrong branch until the folVal check was made explicit. That matches two common traps shown in the thread: branch logic/type mismatches (the real runtime problem) and a few actual bugs picked up by replies — correctly pointed out the duplicate assignment of $q and the incorrect mysql_close usage ($r.mysql_close() concatenates instead of closing the connection), and 's quoting advice highlights why parameterization is a safer approach.

Practical, durable fixes: cast and compare the POST value to a concrete type (for example $fv = (int) $_POST['folVal']; then test === 1 or === 0) so PHP's loose typing does not route execution unexpectedly. Move off the deprecated mysql_* API and use prepared statements (mysqli or PDO) to avoid quoting bugs and SQL injection, and always check the DB driver for errors and affected rows rather than assuming success.

Example pattern (mysqli + prepared statements):

<?php
$mysqli = new mysqli('host','user','pass','db');
$fv   = isset($_POST['folVal']) ? (int) $_POST['folVal'] : null;
$tid  = isset($_POST['ThreadID']) ? (int) $_POST['ThreadID'] : 0;
$user = isset($_POST['Username']) ? trim($_POST['Username']) : '';

if ($fv === 1) {
    $stmt = $mysqli->prepare('INSERT INTO tUserFavourites (ThreadID, Username) VALUES (?, ?)');
    $stmt->bind_param('is', $tid, $user);
    $stmt->execute();
    echo ($stmt->affected_rows === 1) ? 'true' : 'false';
    $stmt->close();
} elseif ($fv === 0) {
    $stmt = $mysqli->prepare('DELETE FROM tUserFavourites WHERE ThreadID = ? AND Username = ?');
    $stmt->bind_param('is', $tid, $user);
    $stmt->execute();
    echo ($stmt->affected_rows > 0) ? 'true' : 'false';
    $stmt->close();
} else {
    echo 'false';
}
$mysqli->close();

Quick troubleshooting checklist (useful for future readers): log $_POST (e.g., error_log(print_r($_POST, true))) to verify values and types; examine the prepared SQL and affected rows; check for trailing whitespace or unexpected characters in Username; verify table constraints/foreign keys or triggers that could block deletes; add a UNIQUE index on (ThreadID, Username) if duplicates are problematic. Given the thread history, the conditional/type fix plus switching to prepared statements will both fix the symptom and make the code more robust going forward.

Recommended Answers

All 4 Replies

In your code you have $q declared in line 19 and 22, the first query statement will be overwrited by the second and only this last will be performed by mysql_query.

At line 23 add or die(mysql_error()); to see if there is an error.

Also change $r.mysql_close(); with mysql_close(); or add as first argument the link identifier, not the query variable: http://php.net/manual/en/function.mysql-close.php

try by writing $q = "DELETE FROM tUserFavourites WHERE ThreadID='".$TID."' AND Username='".$UID."';";

Thanks all...

found the prob..

for some reason php is not recognising the else test for $fv... with your updated SQL manishanibhwani... thanks

just got more explcit - ie $fv must equal a specific value in the else and bingo it worked

Member Avatar for Member #46692

Mark as solved please.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.