Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25763

Not able to delete the database(mySQL) record in PHP, where did i go wrong?

I am trying to delete the records from the users table in mysql,

the code goes like this.

if(isset($_GET['id'])) {
    //create query to delete the record
    $query = "DELETE FROM users WHERE id =" . int($_GET['id'])  or die(mysql_error());

    //execute query
    if($mysqli->query($query)) {
        //print number of affected rows
        echo $mysqli->affected_rows. " row(s) affected";
    }
    else {
        //print error message
        echo "Error in query : $query " . $mysqli->error;
    }
}
else {
    echo "Could not Execute the Delete query";
}

at the same time i am iterating the records from the users table in the database and it goes like this.

//query to get records
$query = "SELECT * FROM users";
//execute query
if($result = $mysqli->query($query)) {
    // see if any rows were returned
    if($result->num_rows > 0) {
        // if yes then print one after another
        echo "<table cellpadding=10 border=1>";
        while($row = $result->fetch_array()) {
            echo "<tr>";
            echo "<td>" .$row[0] . "</td>";
            echo "<td>" .$row[1] . "</td>";
            echo "<td>" .$row[2] . "</td>";
            echo "<td><a href =" . $_SERVER['PHP_SELF']. "?id" .$row[0]. ">Delete</a></td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    $result->close();
}

the problem is, i am able to get the records from the database and display it in the browser but when i try to delete the record the first condition does not pass i.e if(isset($_GET['id'])) instead it goes to else condition and print the message "Could not Execute the Delete query " , i guess it is not able to fetch the $_GET['id'] so only it refuses to enter the if condition,

P.S :i would appreciate if someone explains me in simple words, i am a newbie to programming, thanks..

Upvotes: 1

Views: 268

Answers (2)

Artefacto
Artefacto

Reputation: 97845

"DELETE FROM users WHERE id =" . int($_GET['id'])  or die(mysql_error());

Shouldn't it be intval instead? There's no function int in PHP. There's also (less preferably) the cast to int, like this: (int) $_GET['id']).

Upvotes: 1

Pekka
Pekka

Reputation: 449813

You are missing an =:

echo "<td><a href =" . $_SERVER['PHP_SELF']. "?id=" .$row[0]. ">Delete</a></td>";
                         HERE -------------------^ 

Upvotes: 6

Related Questions