为什么echo在PHP类中不起作用?

nbnkbykc  于 2023-02-15  发布在  PHP
关注(0)|答案(1)|浏览(183)

我在一个类中编写了一个名为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();

?>
gg0vcinb

gg0vcinb1#

如注解中所建议,您的代码对SQL injections开放,请尝试改用parameterized prepared statements

header()函数在页面加载之前重定向用户,因此脚本被编写但从未显示,因为新页面现在紧接着加载。
一种解决方案是使用$_SESSION,它可以像这样:
在您的DeleteProgram类PHP文件上:

# [...]
session_start();
# [...]
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>';
        $_SESSION['swal'] = [
            'title' => "Deleted Successfully!",
            'message' => "Program has been deleted",
            'status' => "success"
        ];
        header("Location: ../php/program.php");
        exit();
    }catch(PDOException $e){
        # [...]
    }
}
# [...]

../php/program.php文件中(<body>中的某个位置):

# [...]
session_start();
# [...]
<?php if(isset($_SESSION['swal'])) {
    $title = $_SESSION['swal']['title'];
    $message = $_SESSION['swal']['message'];
    $status = $_SESSION['swal']['status'];
    echo "<script>swal($title, $message, $status);</script>";
} ?>
  • 我也建议你不要把CSS样式放在你的代码中。它的编写位置不是很可靠。因为你的swal()函数需要你放置一个<script>标签来使用,考虑把你的<style>标签放在它旁边。*

相关问题