Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    Junaid Qadir
    @JunaidQadirB
    Hi guys
    yt94dev
    @yt94dev
    hi
    one help me?can any
    MasterHans
    @MasterHans

    Hi everyone! Can you help me in one question about inserting in databse using PDO.

    I create class for working with databases.

    To connect and work with database I use PDO and embed it inside __construct method.

    public function construct()
    {
    $config = include(
    DIR . '/../../config/config.inc');
    $dsn = $config['driver'] . ':host=' . $config['host'] . ';dbname=' . $config['dbname'];

        try {
            $this->dbh = new \PDO($dsn, $config['login'], $config['password']);
            $this->dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        } catch (\PDOException $e) {
            $error = new View();
            $error->error = $e->getMessage();
            $error->display('403.php');
        }
    }

    And than I execute SQL query by this method:

    public function execute($sql,$params=[])
    {
    $sth = $this->dbh->prepare($sql);
    return $sth->execute($params);
    }

    And here it is Insert method:

    protected function insert()
    {
    $cols = array_keys($this->data);

        $data = [];
        foreach ($cols as $col) {
            $data[':' . $col] = $this->data[$col];
        }
    
        $sql = '
          INSERT INTO ' . static::$table . '
          (' . implode(', ',$cols) . ')
          VALUES
          (' . implode(', ',array_keys($data)) . ')
          ' ;
    
    
        $db = new DB();
        $db->execute($sql,$data);
    
        $column_id = static::$table . '_id';
        $this->$column_id = $db->getLastRecID();
    
    }

    Can I put inside insert() $_POST array without any sanitization?
    I mean is PDO sanitize and escape all the bad things by itself?