如何在类中插入查询?

时间:2016-04-25 12:06:54

标签: php class pdo

我正在上一个班级,我想检查是否所有内容都已填写,如果所有内容都已填入,然后插入数据库,但我仍然坚持如何插入我的班级,所以我希望你们能帮忙我。我从来没有遇到过这个问题的错误。

以下是代码:

<?php


class clsCatCheck
{

    private $catName;

    public function __construct($catName)
    {
        $this->setCatName($catName);
    }

    public function setCatName($catName)
    {
        $connect = new PDO('mysql:host=hostname;dbname=dbname', "username", "password");

            $select = $connect->prepare('SELECT * FROM category');
            $row = $select->fetch();

            if (isset($_POST['addCat'])) {
                if (empty($_POST['catName'])) {
                    throw new Exception('Geen categorienaam is ingevuld<br />');
                }
                //if (strlen($_POST['catName'] <= 4)) {
                  //  throw new Exception('De categorienaam moet minimaal 4 letters of langer zijn<br />');
                //}
                if ($_POST['catName'] == $row[1]) {
                    throw new Exception('Deze categorienaam bestaat al<br />');
                }
            }
            else {
                $query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName = catName)");
                $query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);
                $query->execute();
            }

        $this->catName = $catName;
    }

    public function getCatName()
    {
        return $this->catName;
    }
}

已经感谢您的帮助。 如果您想要更多代码,请询问。

1 个答案:

答案 0 :(得分:2)

您没有正确绑定参数。

更正后的代码:

$query = $connect->prepare("INSERT INTO category (catName) VALUES (:catName)");
$query->bindParam(':catName', $_POST['catName'] ,PDO::PARAM_STR);