我使用以下PHP代码从mysql数据库中删除我的数据。它正在为我工作,但它将我重定向到另一个名为delete_ac.php
的页面。我想保持它在同一个页面(index.php
),如果可能的话,我想使用jquery,以便数据被删除,而不重定向页面。
index . php
<?php
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
?>
<tr>
<td bgcolor="#FFFFFF" style="border:1px solid black" >
<?php echo $row[0].' '; ?>
</td>
<td bgcolor="#FFFFFF" style="border:1px solid black">
<?php echo $row[1]; ?>
</td>
<td bgcolor="#FFFFFF">
<a href="delete_ac.php?id=<?php echo $row[0]; ?>">delete</a>
</td>
</tr>
<?php
}
?>
<?php include 'footer.php'; ?>
delete.ac.php
<?php
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbname");
$tbl_name="tablename"; // Table name
// get value of id that sent from address bar
$id=$_GET['id'];
// Delete data in mysql from row that has this id
$sql="DELETE FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
// if successfully deleted
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='index.php'>Back to main page</a>";
}
else {
echo 'Error';
}
?>
<?php
// close connection
mysql_close();
?>
一个简单的答案是:
- 在锚中包含一个delete类。
<td bgcolor="#FFFFFF"><a class="delete" href="delete_ac.php?id=<?php echo $row[0]; ?>">delete</a></td>
-
将点击绑定到jquery
$('a.delete').on('click', function(e){ var href = $(this).attr('href'); $.ajax({ 'url' : href, 'type' : 'GET', 'success' : function(data) { alert('Data: '+data); }, 'error' : function(request,error) { alert("Error"); } }); });
正如其他人提到的,查看SQL预处理语句。
要回答您的问题,您将使用以下ajax调用
$.ajax({
method: "POST",
url: "delete.ac.php",
data: { id: PUT_YOUR_ID_VALUE}
});
,将delete.ac.php
中的$id=$_GET['id'];
改为$id=$_POST['id'];
这是一个新的index.php
,它使用PDO,并消除了对第二个单独页面的需要。它并不完美,有一些东西仍然可以被清理,但这就是我如何改变它(同时试图保持它尽可能接近你发布的代码)
<?php
//Run the following code if and only if a POST
//request is made to this page.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("dbname");
//This is really important. This is a predefined statement
//the code you had is at risk for SQL injection. Please read up on this
$sql = "DELETE FROM :TABLENAME WHERE id = :ID";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':ID', $_POST['id']);
$stmt->bindParam(':TABLENAME', "tablename"); //put tablename here
$stmt->execute();
}
// This ends the 'POST' code
//
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
?>
<tr>
<td bgcolor="#FFFFFF" style="border:1px solid black" >
<?php echo $row[0].' '; ?>
</td>
<td bgcolor="#FFFFFF" style="border:1px solid black">
<?php echo $row[1]; ?>
</td>
<td bgcolor="#FFFFFF">
<a href="javascript:delete(<?php echo $row[0]; ?>);">delete</a>
</td>
</tr>
<?php
}
?>
<script>
//We're creating a javascript function that will be called
//when the user clicks 'delete'. It takes the ID and passes it
//in the AJAX call
function delete(id){
$.ajax({
method: "POST",
url: "index.php",
data: { id: id}
});
}
</script>
<?php include 'footer.php'; ?>