如何在php mysql中创建删除函数?

时间:2018-03-14 21:55:05

标签: php

我做了一个从更多表中删除的功能,但它不起作用?

//the 'id' is came through URL so why it does not work
$id = $_GET['id'];
del($id, "DELETE FROM `companies` WHERE id=$id");

function del($id, $query){
    try {
        $con->query($query);
        mysqli_commit($con);
        echo 'Deleted';
    } catch (Exception $ex) {
        mysqli_rollback($con);
        echo $ex->getTraceAsString();
    }
}

2 个答案:

答案 0 :(得分:1)

假设$con与您调用函数的范围相同,请尝试此操作。

//the 'id' is came through URL so why it does not work
$id = $_GET['id'];
del($con, "DELETE FROM `companies` WHERE id=$id");

function del($con, $query){
    try {
        $con->query($query);

        mysqli_commit($con);
        echo 'Deleted';
    } catch (Exception $ex) {
        mysqli_rollback($con);
        echo $ex->getTraceAsString();
    }
}

答案 1 :(得分:0)

您应该使用预准备语句来防止SQL注入攻击:

$id = $_GET['id'];
$sql = "DELETE FROM `companies` WHERE id=?";
del($id, $sql, $con);

function del($id, $sql, $con){
    try {
        $result = $con->prepare($sql);
        $result->bind_param('i', $id);
        $result->execute() === true ? 'Successfully deleted' : 'Failed: '.$con->error;            
    } catch (Exception $ex) {
        mysqli_rollback($con);
        echo $ex->getTraceAsString();
    }
}