如何使用参数化的PHP PDO删除MySQL事件?

时间:2014-12-23 19:22:10

标签: php mysql

    public function dMySQLEvent($my_env, $my_event_name) {

        $my_success = 0;
        $my_message = '';

        try {

            # declare & set variables using $my_env
            list ($db_dbdriver, $db_hostname, $db_database, $db_username, $db_password) = Connection::dbConnect($my_env);

            # set default timezone

            # create & set connection

            # WORKS
                # $conn->exec("DROP EVENT IF EXISTS " . $my_event_name . ";");

            # DOES NOT WORK
                # Prepare an SQL statement
                $my_sql = "DROP EVENT IF EXISTS :My_Event_Name";
                $stmt = $conn->prepare($my_sql);

            # bind parameters to prevent SQL Injection
            $stmt->bindValue(':My_Event_Name', $my_event_name);

            # execute the SQL statement
            $stmt->execute();

            # closes the cursor, enabling the statement to be executed again
            $stmt->closeCursor();

            # close & unset the connection
            $stmt = null;
            unset($stmt);
            $conn = null;
            unset($conn);

            # Set success value to TRUE
            $my_success = 1;
            $my_message = 'success';

        } catch(PDOException $e) {

            # Append error message to error log

        }

        return array($my_success, $my_message);

    }

1 个答案:

答案 0 :(得分:4)

您只能将传递给预先准备好的语句。这就是重点。如果你可以改变查询本身,我们就会回到SQL注入。

所以,不,你不能使用SQL标识符的语句参数。如果您有一组固定的可能事件,请使用白名单。否则你必须手动转义并过滤输入(这是冒险的,不推荐)。