I am creating a website using PHP PDO oops concept. For like - I want to count columns for different columns. I have created a function in a class. I follow all steps to secure data (SQL injection). My function -
public function count_by_id($table,$col,$val)
{
$table=$this->sanitize($table,'string');
$col=$this->sanitize($col,'string');
$val=$this->sanitize($val,'string');
$sql= "SELECT count(*) FROM $table WHERE $col=:val";
$stmt = $this->dbConnection->prepare($sql);
$stmt->bindParam(':val', $val, PDO::PARAM_STR);
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
return $number_of_rows;
}
$table is a static variable that will not change any value. I use it only for table name and also the same for column name. The table and col values will not be changed by the end user. The end user will change only $val value and I have bound that value using a prepared statement.
Like - Calling a function -
count_by_id('users','username',$username);
The users and username will not change but $username will change and I have bound it. Is there any reason for SQL injection or not? I am not getting the table name and column name from the form. I can use it for different table and column like this-
count_by_id('posts','slug',$slug);
I am totally confused because many programmers are doing like me and many say this may be the reason for SQL injection. What is your view on that ?