tags:

views:

39

answers:

2
$html="";
$sql="SELECT * FROM tiger;";
$rs=mysql_query($sql);
while($row=mysql_fetch_array($rs)){

    $html.=
            '<tr><td align="left"><img src="'.$row['image'].'" width="200" height="150" /></td>
                <td align="center" style="font:bold">'.$row['name'].' </td>
            <td align="center"><input type="submit" name="Submit" value="Delete" />
            <input name="id" type="hidden" value="'.$row['id'].'" /> </td>

            </tr>'
            ;
    }
if($_REQUEST['Submit']){

$sql1="delete image from tiger where id='".$_REQUEST['id']."'";
$query=mysql_query($sql1);
}

Now this $html is echoed afterwards. so in output im getting 1st rhe image, then d name of the image and then a button. now what i want is wen i click the delete button the respective row is deleted from database. which is not happening in the above code as it is unable to fetch the respective id. so pleaser help how can i do that?

A: 

In your HTML you have as many hidden fields as you have rows in your database, ALL of them with the name "id".

For a quick fix, use a regular link and use the GET-parameter, like this <a href="' . $_SERVER['PHP_SELF'] . '?id=' . $row['id'] . '">delete</a>.

If you really want to use buttons, you'll have to add a form tag around each of your buttons.

Select0r
+2  A: 

Did you add a form element to this table? I replaced $_REQUEST by $_POST, try to avoid using $_GET. A malicious user who knows your delete URL could trick you to click a link (e.g. tinyurl), which opens another set of links: the page deleting all your records. Try this:

$html="";
$sql="SELECT * FROM tiger;";
$rs=mysql_query($sql);
if(!$rs){
    echo 'Query failed...';
    // and log the error, mysql_error()
}
while($row=mysql_fetch_array($rs)){

    $html .=
            '<tr><td align="left"><img src="'.urlencode($row['image']).'" width="200" height="150" /></td>
                <td align="center" style="font:bold">'.htmlentities($row['name']).' </td>
            <td align="center"><form action="" method="post"><input type="submit" name="Submit" value="Delete" />
            <input name="id" type="hidden" value="'.$row['id'].'" /></form> </td>

            </tr>'
            ;
    }
if($_POST['Submit'] && isset($_POST['id']) && ctype_digit($_POST['id'])){

$sql1="delete image from tiger where id='".$_POST['id']."'";
$query=mysql_query($sql1);
if(!$query){
   echo 'Error....';
   //and log mysql_error() somewhere
}
else{
   echo 'Deletion succesful';
}
Lekensteyn
Thank you so much! it worked....
champ