我在一个类中编写了一个名为deleteProgram()
的删除函数,一切都很好,但我想添加一些javascript代码。
<?php
include_once 'db.inc.php';
class DeleteProgram extends Dbh{
public function deleteProgram(){
if(isset($_GET['deleteid'])){
$id = $_GET['deleteid'];
$sql = "DELETE FROM tblprogram WHERE id='$id';";
$result = $this->connect()->query($sql);
header("Location: ../php/program.php");
exit();
}
}
}
$delete = new DeleteProgram;
$delete->deleteProgram();
?>
这就是我所做的,我在deleteProgram()
函数的if语句中创建了一个try/catch,然后使用echo来运行javascript代码,但是它没有显示任何内容,所以这就是卡住的地方。
<?php
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
include_once 'db.inc.php';
class DeleteProgram extends Dbh{
public function deleteProgram(){
if(isset($_GET['deleteid'])){
$id = $_GET['deleteid'];
$sql = "DELETE FROM tblprogram WHERE id='$id';";
try{
$result = $this->connect()->query($sql);
echo '<style>.swal-text{
text-align: center;
}</style>';
echo '<script>swal("Deleted Successfully!", "Program has been deleted", "success");</script>';
header("Location: ../php/program.php");
exit();
}catch(PDOException $e){
echo '<style>.swal-text{
text-align: center;
}</style>';
echo '<script>swal ( "Delete failed!" , "'.$e->getMessage().'" , "error" );</script>';
exit();
}
}
}
}
$delete = new DeleteProgram;
$delete->deleteProgram();
?>
1条答案
按热度按时间gg0vcinb1#
如注解中所建议,您的代码对SQL injections开放,请尝试改用parameterized prepared statements。
header()函数在页面加载之前重定向用户,因此脚本被编写但从未显示,因为新页面现在紧接着加载。
一种解决方案是使用
$_SESSION
,它可以像这样:在您的
DeleteProgram
类PHP文件上:在
../php/program.php
文件中(<body>
中的某个位置):swal()
函数需要你放置一个<script>
标签来使用,考虑把你的<style>
标签放在它旁边。*