Get variable in while loop based on what user choo

2019-07-14 00:32发布

问题:

I want to delete a single post from deleteupload.php hence I want to access product_id which is the unique identifier of each row after submission. I have wrapped every product in a form element and a submit button. So the page has multiple form elements.

This is my code:

 while ($row = mysql_fetch_array($loop))
 {
  $proID = $row['product_id'];

 echo "<table border='0' width='100%' align='center' class='centrebox'><tr>
 <td width='25%'>".($row['product_name']) . "</td> " . "
 <td width='35%'>".($row['product_disc'])."</td>";

 echo '<td width="40%"><img width="100%" height="300"  src="data:image/jpeg;base64,'.base64_encode( $row['product_image'] ).'"/></td></tr>
 <td><form method="post" action="deleteupload.php">
 <input type="submit" name="$proID" value="Delete"></form></td></table><br>';

}

This while loop iterates through the sql table and echos the columns (product_name, product_disc, and product_image).

回答1:

You could put this in your html/php

       echo '<td width="40%"><img width="100%" height="300"  src="data:image/jpeg;base64,'.base64_encode( $row['product_image'] ).'"/></td></tr>
             <td><form name="form' . $proID . '" class="del_forms" method="post" action="deleteupload.php">
             <input type = "hidden" name="del_item" value="' . $proID .'" />
             <input type="submit" value="Delete" /></form></td></table><br>';

and in your deleteupload.php you would pick up the $proID; as a $_POST['del_item']; variable. Assuming $proID; is the ID number of the item you want to have deleted.

Note that you should be using mysqli not mysql as mysql is regarded as vulnerable to attack. You should also escape/sanitize the $_POST variable to help prevent inject attack.

  (int) $_POST['del_item'];

should achieve that in this case as long as the IDs are already integers. (Won't work if they contain letters.)

You might find this of interest as well: Multiple Forms or Multiple Submits in a Page?



回答2:

<table border='0' width='100%' align='center' class='centrebox'>
<?php 
 while ($row = mysql_fetch_array($loop))
 { 
  $proID = $row['product_id'];
?>
 <tr>
 <td width='25%'><?php ($row['product_name'])?></td> 
 <td width='35%'><?php ($row['product_disc']) ?></td>
 <td width='35%'>
    <a href="deleteupload.php?action=delete&id=<?php echo $proID ?>"></a>   
 </td>

<?php } ?>
</table>

**deleteupload.php**

<?php
if($_GET['action']=='delete'){

    delete query
}
?>


标签: php html mysql web