Currently, I'm working with a PHP database connection class that is in one single file with a construct. Every time I need this connection, I instantiate the class and the construct creates the connection with only having to modify the user, password, DBname and host.
It works fine and I haven't faced any problems with this class. Although I want to start taking security seriously in my web applications, I've been looking for a way to implement security (SQL Inj, XSS, DoS, etc.) and use updated functions, prepared statements, escaping, etc. My problem is that I haven't found a single answer about this exactly because I don't call the mysqli_connect
function in index.php. I just create the object for the Connection
class and use it.
<?php
class Connection {
private $connection;
private $host='localhost';
private $user='user';
private $pass='pass';
private $database='dbname';
private $n=0;
function __construct() {
$this->connection = mysqli_connect($this->host, $this->user, $this->pass, $this->database);
mysqli_query($this->connection,"SET NAMES 'utf8'");
}
function sql($sql) {
if (is_array($sql)) {
foreach ($sql as $s) {
$res = mysql_query($s);
if (mysql_errno()) echo mysql_error().'<br>';
$this->n++;
}
} else {
$res = mysqli_query($this->connection,$sql);
if (mysql_errno()) echo mysql_error().'<br>';
$this->n++;
}
return $res;
}
function __destruct() {
if (is_resource($this->connection) )
mysql_close($this->connection);
}
function getLink() {
return $this->connection;
}
}
So if I want to Create, Read, Update, Delete Something I do this in another file: User.php (Which i want to use the new method I'm asking for and use prepared statements for the Queries here and escape functions)
<?php
// Declare a variable
private $user;
// Setter
function setUser($val){
$this->user = $val;
}
// Create Function to CreateUser
function CreateUser(){
$con = new Connection();
$sql = "INSERT INTO user (DATA) VALUES(DATA)";
$con->sql($sql);
}
// Same for all CRUD i just change the Query of course.
?>
<?php
// At the index.php i do this:
include_once 'User.php';
$user = new User();
if(isset($_POST['createUserButton'])){
// $The variable i set in my User Class
$user = $_POST['user'];
// Then the Setter
$user->setUser($user);
// Then execute the Function
$user->CreateUser();
}
?>
I'm trying to translate this class using:
- New versions of functions
- Using
try
/catch
- Security
I'm just trying to have as many points of view from more experienced developers. I'm a few months old at this and I'm trying to look at different methods to code so I can create my own.