dongwh1992
2017-08-29 19:46
浏览 8
已采纳

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...

this is my function:

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";
}

}
?>

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongye9820 2017-08-30 00:10
    已采纳

    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.

    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.

    Good luck!

    index.php

    <?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 (the class)

    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();
            }
        }
    
    }
    

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doutuo8800 2017-08-29 20:06

    $con = new DB() or just DB()?

    public function AddCategory($cat_name)
    {
        try {
            //$con = DB();  Sometimes size matters!
            $con = new DB();
            if( !$con ){ echo "No Database Connection!"; die();}
    
            $sql = $con->prepare("INSERT INTO category(cat_name)values(:cat_name)");
            $sql->bindParam(":cat_name", $cat_name, PDO::PARAM_STR);
            $sql->execute();
        } catch (Exception $e) {
            exit($e->getMessage());
        }
    }
    
    评论
    解决 无用
    打赏 举报