tags:

views:

47

answers:

2

Hi, 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..

+1  A: 
"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']).

Artefacto
True. Either intval() or (int)$_GET['id']. Still doesn't say why it would go straight to else branch of if.
Mchl
@Mchl Yes, Pekka got it.
Artefacto
yes it should be intval, i was just testing it, i changed it back.. Pekka got the answer and it is worling perfectly fine now..
Ibrahim Azhar Armar
Ahh Pekka, always getting the answers. Not letting anyone else get them! Blast him!
Blair McMillan
+6  A: 

You are missing an =:

echo "<td><a href =" . $_SERVER['PHP_SELF']. "?id=" .$row[0]. ">Delete</a></td>";
                         HERE -------------------^ 
Pekka
hehe, thank you.. i was so dumb, couldnt notice it... :) it is working perfectly fine now...
Ibrahim Azhar Armar