[Solved] php function is not working? [closed]


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

7

solved php function is not working? [closed]