Search code examples
phpmysqlsql-delete

MySQL Delete Item from Table not working


I am trying to delete a record in my db based on the unique id ($id). Is there something wrong with this code? Probably a simple one for you php pro's.

    function delAccount(){  

         mysql_query("DELETE FROM accounts WHERE id=".$id."LIMIT 1");

        }

I get a :

    Fatal error: Can't use function return value in write context in     
    /home/content/53/7311353/html/cca/accounts/include/processAct.php on line 15

My Class that I have powering everything:

    class Accounts
        {

    function Accounts(){
        if (isset($_POST['addacct'])){
            $this->addAccount();
        }elseif(isset($_POST['editacct'])){
            $this->editAccount();
        }elseif(isset($_POST['delacct'])){
            $this->delAccount();
        }else{
            // redirect if loaded without a POST value set
            header("Location: ../index.php?o=illegal&t=nodata");
        }
    }

Solution

  • You should, first of all, put a space between ".$id." and LIMIT so:

    mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");

    Secondly, the $id is NOT available within this function by default. Either do this:

    function delAccount($id) {  
      mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
    }
    

    and use delAccount($id_parameter); in your script to send the ID along with the function. Or try this:

    function delAccount() {  
      global $id;
      mysql_query("DELETE FROM accounts WHERE id=".$id." LIMIT 1");
    }
    

    then you can call this function after you set the value of $id somewhere else in your code.