简体   繁体   中英

Deleting entry from MySQL table using PHP variable

I'm pretty sure this question has been asked many times, I've searched the web and still can't figure out the solution to this problem.

Here's the code (I know it is not injection proof):

To display all the entry in the table

<?php
$query="SELECT * FROM testimony";
$result=mysql_query($query);
while($row=mysql_fetch_array($result))
{
?>
<div>
  <form name="testimonial" action="admintestimony.php" method="post">
  <table border="0">
    <tr>
      <td>Username:</td>
      <td></td>
      <td><input type="text" name="testyname" value='<?php echo $row[0];?>' readonly></td>
    </tr>
    <tr>
      <td>Testimony:</td>
      <td></td>
      <td><textarea name="txttesty" cols="50" rows="10" readonly><?php echo $row[1];?></textarea></td>
    </tr>
    <tr>
      <td><input type="submit" name="approve" value="Approve"></td>
      <td></td>
      <td><input type="submit" name="reject" value="Reject"></td>
    </tr>
  </table>
  </form>
</div>
<?php
}
?>

To check whether approve or reject is pressed

<?php
session_start();
include('connection.php');
$testyname=$_POST['testyname'];
if (isset($_POST['approve']))
{
    header("location:testimonyapproved.php");
}
else if (isset($_POST['reject']))
{
    header("location:reject.php");
}
?>

If reject is pressed

<?php
session_start();
$testyname=$_POST['testyname'];
include('connection.php');
mysql_query("SELECT * FROM testimony");
mysql_query("DELETE FROM 'transaction' WHERE 'transaction' 'name' = $testyname");
header("location:testimonyrejected.php");
?>

Any help would be appreciated, thanks.

its your SQL

 DELETE FROM `transaction` where `name` = $testyname 

will likely work better

Your SQL is wrongly formatted (quotes in wrong places). I've added some comments in this improved code, check it out.

mysql_query("SELECT * FROM testimony"); //this line is useless and you can delete it
mysql_query("DELETE FROM transaction WHERE name = '".$testyname."'"); //this line contained wrong syntax

Please note that mysql_ functions are deprecated in new versions of PHP. Check this post on more info on this subject.

Also you might want to prevent SQL injection in the $testmyname variable. This guide will help you with tat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM