-3

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

}
?>

Logan 96
  • 91
  • 8

2 Answers2

1

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

  • Great advice but it's better to set the `error_reporting` and `display_errors` in the dev environment's `php.ini` file (if possible) – Phil Aug 30 '17 at 00:46
  • Indeed, @Phil, this is a good choice too, if you are on a dev machine and on a virtual host basis. Thanks. In this case I just wanted to show Arijit how he can discover the possible errors, warnings, etc... on the fly. –  Aug 30 '17 at 01:12
  • @ARIJITDASGUPTA You are welcome. When you find your final solution please give us the results. I, personally, am very curious about where the problem lies. Thanks. Bye. –  Aug 31 '17 at 20:29
  • @aendeerei I've edited my code that's working properly... and again thanks for your support... – Logan 96 Sep 01 '17 at 00:07
  • @ARIJITDASGUPTA Any time, with pleasure. Please tell me, what was the problem? –  Sep 01 '17 at 07:30
  • IDK the which was the problem... I just rewrote the function and now it's working.:P – Logan 96 Sep 02 '17 at 10:21
  • @ARIJITDASGUPTA Well then, important is that it's working ;-) Note that it would be a lot better if you would create a db adapter class to handle all those db operations and exception handlings for you. –  Sep 02 '17 at 11:37
0

$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());
    }
}
Prince Adeyemi
  • 724
  • 6
  • 12