php功能无法正常工作

php功能无法正常工作

本文介绍了php功能无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过一个函数添加一些内容,但是它无法正常工作..我已经调试了很多次..但是找不到任何错误..如果有人解决这个问题,这将非常有帮助.

I'm trying to add some content through a function but it's not working.. I've been debugged many times.. but couldn't find any error.. It'll be very helpful if anyone resolve this...

这是我的功能

public function AddCategory($cat_name,$uploader_id)
{
    try {
        $con = DB();
        $sql = $con->prepare("INSERT INTO category(cat_name,uploader_id,uploaded_on) VALUES (:cat_name,:uploader_id,NOW())");
        $sql->bindParam("cat_name", $cat_name, PDO::PARAM_STR);
        $sql->bindParam("uploader_id", $uploader_id, PDO::PARAM_STR);
        $sql->execute();
        return $con->lastInsertId();
    } catch (PDOException $e) {
        exit($e->getMessage());
    }
}

这就是我正在使用的地方

And this is where I'm using it

<?php


$add_cat_error_message = '';
$obj_add_cat = new Add();
if (!empty($_POST['add_cat'])) {
if ($_POST['cat_name'] == "") {
    $add_cat_error_message = 'Category name is required!';
}  else if ($obj_add_cat->ChkCat($_POST['cat_name'])) {
    $add_cat_error_message = 'category is already in use!';
} else {
    $cat = $obj_add_cat->AddCategory($_POST['cat_name'],$_SESSION['user_id']);
   echo "added";
}

}
?>

}
?>

推荐答案

在您的情况下,未知数太多.首先,您必须启用适当的错误报告级别,并且-仅出于开发目的-让错误显示在屏幕上.其次,在重要的错误/失败情况下,您的异常处理代码将无法解决这些问题.

In your case there are too many unknowns. First of all you must enable a proper error reporting level and - only for development - let the errors be displayed on screen. Second, there are important error/failure situations which you are not covering with your exception handling code.

此外,我将使用bindValue()代替bindParam().对于bindValue(),可以在执行准备好的语句之前验证绑定输入参数的结果.

Also, I would use bindValue() instead of bindParam(). In the case of bindValue() you can validate the result of binding the input parameter(s) before the prepared statement is executed.

我写了一段代码,希望对您有所帮助.

I wrote a piece of code which, I hope, will be of some help for you.

祝你好运!

<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);


/*
 * =====================================================
 * Create a PDO instance as db connection - to mysql db.
 * =====================================================
 */
try {
    // Create PDO instance.
    $connection = new PDO(
            'mysql:host=localhost;port=3306;dbname=yourDb;charset=utf8'
            , 'yourDbUsername'
            , 'yourDbPassword'
    );

    // Assign driver options.
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $connection->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
    $connection->setAttribute(PDO::ATTR_PERSISTENT, TRUE);
} catch (Exception $exc) {
    echo '<pre>' . print_r($exc, TRUE) . '</pre>';
    exit();
}

/*
 * =====================================================================
 * Create class instance (with connection as argument) and run the code.
 * =====================================================================
 */
$add_obj = new Add($connection);

if (isset($_POST['add_cat']) && !empty($_POST['add_cat'])) {
    if (isset($_POST['cat_name']) && !empty($_POST['cat_name'])) {
        $caid = $add_obj->AddCategory($_POST['cat_name']);

        echo 'Added with id: ' . $caid;
    } else {
        echo 'Please provide the category name!';
    }
} else {
    echo 'Please provide the add_cat!';
}

Add.php(该类)

class Add {

    private $connection;

    /**
     *
     * @param PDO $connection Db connection.
     */
    public function __construct(PDO $connection) {
        $this->connection = $connection;
    }

    /**
     * Add category.
     *
     * @param string $categoryName Category name.
     * @throws UnexpectedValueException
     */
    public function AddCategory($categoryName) {
        try {
            /*
             * Prepare and validate the sql statement.
             *
             * --------------------------------------------------------------------------------
             * If the database server cannot successfully prepare the statement, PDO::prepare()
             * returns FALSE or emits PDOException (depending on error handling settings).
             * --------------------------------------------------------------------------------
             */
            $sql = 'INSERT INTO category (
                        cat_name
                    ) VALUES (
                        :cat_name
                    )';

            $statement = $this->connection->prepare($sql);

            if (!$statement) {
                throw new UnexpectedValueException('The sql statement could not be prepared!');
            }

            /*
             * Bind the input parameters to the prepared statement.
             *
             * -----------------------------------------------------------------------------------
             * Unlike PDOStatement::bindValue(), when using PDOStatement::bindParam() the variable
             * is bound as a reference and will only be evaluated at the time that
             * PDOStatement::execute() is called.
             * -----------------------------------------------------------------------------------
             */
            // $bound = $statement->bindParam(':cat_name', $categoryName, PDO::PARAM_STR);
            $bound = $statement->bindValue(':cat_name', $categoryName, PDO::PARAM_STR);

            if (!$bound) {
                throw new UnexpectedValueException('An input parameter could not be bound!');
            }

            /*
             * Execute the prepared statement.
             *
             * ------------------------------------------------------------------
             * PDOStatement::execute returns TRUE on success or FALSE on failure.
             * ------------------------------------------------------------------
             */
            $executed = $statement->execute();

            if (!$executed) {
                throw new UnexpectedValueException('The prepared statement could not be executed!');
            }

            /*
             * Get last insert id.
             */
            $lastInsertId = $this->connection->lastInsertId();

            if (!isset($lastInsertId)) {
                throw new UnexpectedValueException('The prepared statement could not be executed!');
            }
        } catch (Exception $exc) {
            echo '<pre>' . print_r($exc, TRUE) . '</pre>';
            exit();
        }
    }

}


编辑1 :刚刚颠倒了"index.php"中的HTTP POST验证.


EDIT 1: Just inverted the HTTP POST validations in "index.php".

这篇关于php功能无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 20:46