如何避免mysqli连接以及如何使用real_escape_string?

Here an excerpt from php class:

DB.class.php

class DB {    
    protected $db_name = '';
    protected $db_user = '';
    protected $db_pass = '';
    protected $db_host = '';
    protected $connection;

    public function connect() {
        $this->connection = mysqli_connect($this->db_host, $this->db_user, $this->db_pass);
        mysqli_select_db($this->connection, $this->db_name);

        return true;
    }

    public function processRowSet($rowSet, $singleRow = false) {
        $resultArray = array();
        while ($row = mysqli_fetch_assoc($rowSet)) {
            array_push($resultArray, $row);
        }

        if ($singleRow === true)
            return $resultArray[0];

        return $resultArray;
    }

    public function insert($data, $table) {
        $columns = "";
        $values = "";

        foreach ($data as $column => $value) {
            $columns .= ($columns == "") ? "" : ", ";
            $columns .= $column;
            $values .= ($values == "") ? "" : ", ";
            $values .= $value;
        }

        $sql = "insert into $table ($columns) values ($values)";

        mysqli_query($this->connection, $sql) or die(mysqli_error($this->connection));

        //return the ID of the user in the database.
        return mysqli_insert_id($this->connection);
    }
}

insert-entry.php

require_once 'db.php';

$headline = $_POST['headline'];
$description = $_POST['description'];

$data = array(
        'headline' => $headline,
        'description' => $description
    );

$db->insert($data, 'entries');´

I have three questions on the professional use of this class:

  • Avoding mysqli connection: The class was mysql before and I changed it to mysqli. Is there any way to avoid that I always need to pass the mysql connection as a parameter when I want to do mysqli operations, such as mysqli_query()?
  • Sanitizing user input: How can I build in $db->real_escape_string? I want it to be applied for all values that come from the user and go into my database. Is it something I can add in the insert function in DB.class.php or do I have to apply this in my outer php files, for example insert-entry.php in this example?
  • Catching an error: In an outer php file such as insert-entry.php in this example, how can I catch an error of a function such as the $db->insert() function? My goal is that if an error occurs the user is directed to an error page (via header:location). Important: I want to be able to create individual error handlings in different php files.