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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据