PDO custom class and security - php

I am trying to create my own class to work/play with database with PDO. I am having the following method in my class:
private function connect(){
try{
$this->con = new PDO("mysql:host={$this->host};dbname={$this->db_name};charset=utf8", $this->db_user, $this->db_pass);
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->con->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $ex){
$this->catchError($ex);
}
}
is there any thing vulnerable in my connection? while i am providing other CRUD method in my class like this:
public function getRecordSet($sql,$bindVars=array()){
$ary = array();
try{
$this->connect();
$obj = $this->con->prepare($sql);
if(count($bindVars) > 0){
$obj->execute($bindVars);
}
else{
$obj->execute();
}
$ary = $obj->fetchAll();
}catch(PDOException $ex){
$this->catchError($ex); //Production Server: send exception through email
//echo($ex->getMessage()); //Developer Machine: Display Exceptions in browser
}
$this->con = null;
return $ary;
}//getRecordSet()
In this query users will retrive recordset as an array() using the following way for example:
$sno = 1;
$user_name = '%hussain%';
$aray = array(':sno'=>$sno,':user_name'=>$user_name);
foreach($crud->getRecordSet("SELECT * FROM users WHERE sno = :sno AND user_name LIKE :user_name",$aray) as $row){
echo('<br>'.$row['user_name']);
echo('<br>'.$row['user_password']);
echo('<br>'.$row['date_reg']);
}
Please let me know if there is anything goes wrong and makes my class vulnerable?
Thanks in advance.
Shah

Change function to
public function getRecordSet($sql, $bindVars=array()){
$obj = $this->con->prepare($sql);
$obj->execute($bindVars);
return $obj->fetchAll();
}
however, it's rather matter of sanity, not security

Related

What arguments should be passed to PDO::__construct()?

I'm a new in web programming and would ask the advice for code below.
I have the code in class Database. There is it. As you see there's a connect to database with mysqli. And this code work.
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runBaseQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
function runQuery($query, $param_type, $param_value_array) {
$sql = $this->conn->prepare($query);
$this->bindQueryParams($sql, $param_type, $param_value_array);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultset[] = $row;
}
}
if(!empty($resultset)) {
return $resultset;
}
}
function bindQueryParams($sql, $param_type, $param_value_array) {
$param_value_reference[] = & $param_type;
for($i=0; $i<count($param_value_array); $i++) {
$param_value_reference[] = & $param_value_array[$i];
}
call_user_func_array(array(
$sql,
'bind_param'
), $param_value_reference);
}
function insert($query, $param_type, $param_value_array) {
$sql = $this->conn->prepare($query);
$this->bindQueryParams($sql, $param_type, $param_value_array);
$sql->execute();
}
function update($query, $param_type, $param_value_array) {
$sql = $this->conn->prepare($query);
$this->bindQueryParams($sql, $param_type, $param_value_array);
$sql->execute();
}
I have to write this class in PDO. I've done it, but something is wrong. I try to connect my Database and get the error
Fatal error: Uncaught TypeError: PDO::__construct() expects parameter 4
class DB {
private $host = "";
private $user = "";
private $password = "";
private $database = "";
private $pdo;
function __construct() {
$this->pdo = $this->connectDB();
}
function connectDB() {
try
{
$pdo = new PDO($this->host,$this->user,$this->password,$this->database);
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage();
}
die();
}
function runBaseQuery($query)
{
$result = $pdo->query($query);
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
$resultset[] = $row;
}
if (!empty($resultset))
return $resultset;
}
function runQuery($query, $param_type, $param_value_array) {
$sql = $pdo->prepare($query);
$pdo->execute($sql, $param_type, $param_value_array);
$result = $pdo->fetchAll(PDO::FETCH_ASSOC);
if ($result->num_rows > 0) {
while ($row = $pdo->fetchAll(PDO::FETCH_ASSOC)) {
$resultset[] = $row;
}
}
if(!empty($resultset)) {
return $resultset;
}
}
function bindQueryParams($sql, $param_type, $param_value_array) {
$param_value_reference[] = & $param_type;
for($i=0; $i<count($param_value_array); $i++) {
$param_value_reference[] = & $param_value_array[$i];
}
call_user_func_array(array(
$sql,
'bind_param'
), $param_value_reference);
}
function insert($query, $param_type, $param_value_array) {
$sql = $pdo->prepare($query);
$pdo->execute($sql, $param_type, $param_value_array);
}
function update($query, $param_type, $param_value_array) {
$sql = $pdo->prepare($query);
$pdo->execute($sql, $param_type, $param_value_array);
}
}
But my the new code don't work. Where is the problem?
Your new class has multiple problems. The one you are asking about can be solved by understanding how to connect properly with PDO and what DSN is. For this I have to refer you to this awesome article https://phpdelusions.net/pdo#dsn
Take this DSN for example:
mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4
driver^ ^ colon ^param=value pair ^semicolon
You start by specifying which DB driver you would like to use: mysql:. After this comes a list of key-value pairs separated by a semicolon. The order should be host, DB name, and charset. You should specify all of these values.
Your DSN is your first argument to PDO::__construct(), the second and third is username and password respectively. The third one is an array of options.
Your options array should contain at least two values. You need to enable error reporting and switch off emulated prepared statements. These are the recommended settings.
Your connection should look at least similar to this:
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO('mysql:host='.$this->host.';dbname='.$this->database.';charset=utf8mb4', $this->user, $this->password, $options);
However, please take note, that the constructor will be called once, and you do not need to put these values in private properties. They can simply be constants or hardcoded in the constructor. You will never need to reuse this values after opening connection.
Your second main mistake is that you are referring in a lot of places to $pdo, but you should be using $this->pdo.
Other notes:
die(); is going to end your whole script. Do not use it.
Do not catch exceptions, just to print out the error message. It defeats the whole purpose of the exceptions.
The method bindQueryParams() seems completely unnecessary. I would recommend you remove it.
runQuery is riddled with mistakes. $pdo->execute() takes in only one argument, which should be the array of values to be bound. There is no need for param type like in mysqli. The while loop is redundant and incorrect.
num_rows does not exist in PDO, and is not needed at all.
None of these method provide any benefit over just plain PDO.
Conclusion:
The class you have written is completely unnecessary and only makes your code more difficult to understand and maintain. While it might have made more sense with mysqli, PDO is simpler to use and does not need to be wrapped in such class. Please read the article linked at the beginning carefully, it will help you a lot.
The PDO connection does not take a 4th parameter for the database name. The DB name is passed in with the host name. So change:
$pdo = new PDO($this->host,$this->user,$this->password,$this->database);
to:
$pdo = new PDO($this->host . ';dbname=' . $this->database, $this->user, $this->password);
For more information see https://www.php.net/manual/en/pdo.connections.php
Additionally, it is unclear what $this->host contains but for PDO if that is just a host path you need to pass in the driver you are using as well, so you might even need to add
mysql:host=
to the start of this. With mysqli this is not required because the only RDBMS mysqli supports is mysql.
So potentially complete answer:
$pdo = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database, $this->user, $this->password);

stmt get_result another way

An example of one of my queries...
public function db_query_select($query, $params, $param_types){
$dbc = $this->dbConnect();
if($stmt = $dbc->prepare($query)){
//prepared.
//move the types to the front of the param array
array_unshift($params, $param_types);
//call the bind param function with the parameters passed in by reference
//bind_param only allows by reference.
call_user_func_array(array($stmt, "bind_param"), $this->paramsToRefs($params));
//binded.
//attempt to execute the sql statement.
if ($stmt->execute()){
$result = $stmt->get_result();
$stmt->close();
$dbc->close();
return $result;
}
}
//must have failed...
return NULL;
}
how can I change stmt get_result(); to something that is accepted by shared servers/hosts without the native driver... mysqlnd.
Anyone know? without changing all of my functions that use this database function.
Thanks.
UPDATED:::: Thanks to #your common sense, See Answer.
I believe this is what I was after. Hope it helps anyone that was having the same problem as myself. PDO vs MySQLi, seems simpler... no user call func or anything like that.
DB HANDLER:
private function dbConnect(){
$config = parse_ini_file($_SERVER['DOCUMENT_ROOT'].'/NTConfig.ini');
try {
$dbc = new PDO('mysql:host='.$config['DB_HOST'].';dbname='.$config['DB_DATABASE'].'', $config['DB_USER'], $config['DB_PASSWORD']);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
return $dbc;
}
public function db_query_select($query, $params){
$dbc = $this->dbConnect();
if($stmt = $dbc->prepare($query)){
//prepared.
//attempt to execute the sql statement.
if ($stmt->execute($params)){
$result = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);
//$stmt->close();
//$dbc->close();
return $result;
}
}
//must have failed...
return NULL;
}
Outside the DBHANDLER
$query = "SELECT error_desc FROM nt_errors WHERE error_code = :ERROR_CODE LIMIT 1";
//array: holds parameters for the query.
$params = array(
':ERROR_CODE' => $code
);
$result = $db->db_query_select($query, $params);
if ($result == NULL){
$errorText = 'ERROR: Failed to retrieve error';
}
else{
//var_dump($result);
$errorText = $result['error_desc'];
PDO is not only much more user friendly than mysqli but also doesn't have any of such a nasty drawbacks. So I strongly suggest to use PDO instead of mysqli.
With DO, the function you're after should be as simple as this
function run($sql, $args = NULL)
{
$pdo = ...;//your means of getting the connection variable
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
After gettin the function's result, you can chain a fetch method to its call, fetchColumn() in your case.
Given your code is mostly procedural, let me suggest you a very simple PDO wrapper I wrote. So the full code would be:
$sql = "SELECT error_desc FROM nt_errors WHERE error_code = ?";
$errorText = DB::run($sql,[$code])->fetchColumn();
if (!$errorText){
$errorText = 'ERROR: Failed to retrieve error';
}
Here DB class is a better replacement of your dbConnect() function, and run() method is a replacement for db_query_select() that actually can be used for any query type, including insert, update or anything.

Set isolation on DB2 with Zend Framework

I need to lock a record while fetching and updating his fields.
It's the first time I need this, so I made a test class to see how thing works(I promise I'll neve make queries in the controller again).
With a browser (chrome) i call testisolationread, with another(FF) testisolationwrite which updates all the times without problems.
I tried with select()->forUpdate() too with same results.
I tried adding "WITH RS USE AND KEEP EXCLUSIVE LOCKS" (because "WITH RS USE AND KEEP UPDATE LOCKS" throws error). So here I am.
Any advice?
Thank you
class Admin_testController extends Myprj_Controller_Main{
public function init(){
parent::init();
}
/**
* #return Strategic_Db_Adapter_Db2
* #throws Zend_Exception
*/
private function _getDb(){
$db = Zend_Registry::get('conn');
return $db;
}
public function testisolationreadAction(){
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$db = $this->_getDb();
try{
$select = $db->select()
->from('MYLIB/MYFILE', array('trim(FIELD01) as FIELD01'))->where("FIELD02 = '002654015-002'");
$stmt = $select->__toString()." WITH RR";
$result = $db->fetchRow($stmt);
sleep(10); //gives me the time to call testisolationwrite
$bind = array('FIELD01' => 'A');
$db->update('MYLIB/MYFILE', $bind, array("FIELD02 = '002654015-002'"));
$db->commit();
} catch(Exception $e){
print $stmt.'<br>';
print $e->getMessage();
$db->rollBack();
}
print '<pre>'.$stmt;
print_r($result);
}
public function testisolationwriteAction(){
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$db = $this->_getDb();
$vals = array('X', 'Y');
for($a = 0; $a < 20; $a++){
try{
$i = $vals[$a % 2];
$bind = array('FIELD01' => $i);
$db->update('MYLIB/MYFILE', $bind, "FIELD02 = '002654015-002'");
print 'SET :'.$i.' '.microtime().'<br>';
$db->commit();
} catch(Exception $e){
$db->rollBack();
}
}
}
}

The lifecycle of an object in PHP

I have two PHP scripts that I included below. Both of them attempt to do the same thing, but one works and one does not. I'm looking for someone to explain what PHP is doing under the covers. I'm new to PHP and I suspect that my Java experience is poisoning my thought process when I work in PHP.
What I'm attempting to do is functionally very simple -- Insert a question into a mySQL database table, retrieve the primary key of the inserted row, and then insert five answers into another table with a foreign key relationship to the question.
My original logic looked like this:
ManageQuestions.php:
<?php
session_start();
include('query.php');
echo "begin <br>";
if (isset($_POST['submit'])) {
echo "manageQuestion <br>";
$query = new Query;
$query->createTransaction();
$query->executeCreateUpdateDelete("INSERT INTO question (question) VALUES ('".$_POST['question']."'); ");
$question_pid = $query->getLastInsertedId();
$query->commitTransaction(); // Need to figure out how to do dirty reads so I can remove this.
echo $question_pid."<br>";
$result = $query->executeRead("SELECT question_pid FROM question where question_pid = '".$question_pid."';");
echo count($result)."<br>";
//if (count($result) === 1) {
$query->createTransaction(); // Need to figure out how to do dirty reads so I can remove this.
foreach($_POST['answer'] as $answer) {
$correctAnswers = 0;
$query->executeCreateUpdateDelete("INSERT INTO answer (question_fid, answer, isCorrect) VALUES ('".$question_pid."','".$answer['answer']."','".$answer['isCorrect']."')");
if ($answer['isCorrect'] === 1) {
$correctAnswers = $correctAnaswers + 1;
if ($correctAnswers > 1){
echo "Failed to insert answers";
$query->rollBackTransaction();
break;
}
}
}
echo "Success";
$query->commitTransaction();
/* } else {
echo "Failed to insert question";
$query->rollBackTransaction();
} */
}
?>
Query.php:
<?php
session_start();
class Query
{
private $host="<censored>";
private $username="<censored>";
private $password="<censored>";
private $db_name="<censored>";
private $pdo;
private $pdo_statement;
private $pdo_exception;
public function executeCreateUpdateDelete($pQuery)
{
$this->pdo_statement = $this->pdo->prepare($pQuery);
return $this->pdo_statement->execute();
}
public function executeRead($pQuery)
{
try
{
$dbh = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
$result = $dbh->query($pQuery);
$dbh = null;
return $result->fetchAll();
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function createTransaction()
{
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
$this->pdo->beginTransaction();
}
public function commitTransaction()
{
$this->pdo->commit();
}
public function rollBackTransaction()
{
$this->pdo->rollBack();
}
public function getLastInsertedId()
{
$this->pdo->lastInsertId();
}
}
?>
When I rewrote my logic to not use a separate query class, I was able to do what I wanted to do. The only thing I've been able to find online about the life cycle of a PHP object is that it begins at the start of a script and ends at the end of a script. Does that imply that my query object is instantiated every time I call one of its methods and garbage collected when that particular method ends? Moving the logic out of that class and into the script caused my logic to work. This is what it looks like now:
ManageQuestions.php:
<?php
session_start();
include('query.php');
echo "Begin <br>";
if (isset($_POST['submit'])) {
echo "manageQuestion <br>";
$host="<censored>";
$username="<censored>";
$password="<censored>";
$db_name="<censored>";
$pdo = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
$stmt = $pdo->prepare("INSERT INTO question (question) VALUES ('".$_POST['question']."'); ");
$stmt->execute();
$question_pid = $pdo->lastInsertId();
echo $question_pid."<br>";
$stmt = $pdo->query("SELECT question_pid FROM question where question_pid = '".$question_pid."';");
$result = $stmt->fetchAll();
echo count($result)."<br>";
foreach($_POST['answer'] as $answer) {
$correctAnswers = 0;
$stmt = $pdo->prepare("INSERT INTO answer (question_fid, answer, isCorrect) VALUES ('".$question_pid."','".$answer['answer']."','".$answer['isCorrect']."')");
$stmt->execute();
}
echo "Success";
}
?>
Even though this fixed my issue, I don't understand why. If someone could explain that, I would be extremely grateful.
Cheers!
Does that imply that my query object is instantiated every time I call one of its methods and garbage collected when that particular method ends?
No. It's per request, not per method call. So the query object is instantiated every time the script is called and it gets unset (and not necessarily garbage collected) when the script ends.
However you could better manage the resource of the PDO object inside your Query class because you create a new instance (which would mean that it connects again to the database server which is not that cheap). So some lazy loading does not seem bad:
class Query
{
...
/** #var PDO */
private $pdo;
...
private function getPdo() {
if (!$this->pdo) {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->db_name", $this->username, $this->password);
}
return $this->pdo;
}
public function executeRead($pQuery)
{
try {
$dbh = $this->getPdo();
$result = $dbh->query($pQuery);
return $result->fetchAll();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function createTransaction()
{
$this->getPdo()->beginTransaction();
}
...

PHP PDO Not returning any data from other class

I have the following script that is not returning any thing at all, the best I've gotten is a var_dump to say bool(false).. There is nothing at all in my error_log and no exceptions are being thrown:
index.php:
require("php/bootstrap.php");
$campaign = new Campaign($_GET['campaign'], $mysql);
bootstrap.php:
define ("MYSQL_USER", "specialagent");
define ("MYSQL_PASS", "supertopsecret");
define ("MYSQL_HOST", "127.0.0.1");
define ("MYSQL_PORT", "3306");
define ("MYSQL_DB", "databasewithsecretinformation");
/* Auto include classes on instantiation */
function __autoload($class_name) {
include 'classes/'.$class_name.'.php';
}
/* Connections */
try {
$mysql = new PDO("mysql:host=".MYSQL_HOST.";dbname=test", MYSQL_USER, MYSQL_PASS);
} catch(PDOException $e) {
die("There was a problem connecting to the database. Error: " . $e->getMessage());
}
Campaign.php
class Campaign {
protected $dbh;
private $campaign_id = "";
private $name = "";
public function __construct ($campaign_id, PDO $db) {
//if ($campaign_id) {
$this->setCampaignID($campaign_id);
$this->dbh = $db;
$this->loadCampaignInfo();
//}
}
public function getCampaignID() {
return $this->campaign_id;
}
public function setCampaignID($id) {
$this->campaign_id = $id;
}
public function __destruct() {
//$this->dbh = null;
}
public function loadCampaignInfo() {
/* Get info from database */
$sql = "SELECT * FROM campaigns WHERE campaign=:campaignID";
try {
echo "trying query...$sql<br />";
if ($this->dbh instanceof PDO) {
$stmt = $this->dbh->prepare($sql);
$stmt->bindParam(":campaignID", $this->campaign_id, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch();
echo "Returned Data: ";
var_dump($row);
} else {
echo "Not a valid PDO resource";
}
} catch (PDOException $e) {
echo "Problem : " . $e->getMessage;
} catch (Exception $e) {
echo "Other problem : " . $e->getMessage;
}
/* Set properties */
}
}
Output:
trying query...SELECT * FROM campaigns WHERE campaign=:campaignID
Returned Data: bool(false)
The problem has nothing to do with PDO.
Returned Data: bool(false) means no row were found to match condition.
Check your table if it contain the data and check input as well.
Check if you are getting the right class from autoload and all the stuff like that.
Also, change your bootstrap connection to
ini_set('display_errors',1);
error_reporting(E_ALL);
/* Connections */
$mysql = new PDO("mysql:host=".MYSQL_HOST.";dbname=test", MYSQL_USER, MYSQL_PASS);
$mysql->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
you may wish also to make the method less bloated too:
/* Get info from database */
public function loadCampaignInfo()
{
$sql = "SELECT * FROM campaigns WHERE campaign=?";
$stmt = $this->dbh->prepare($sql);
$stmt->execute([$this->campaign_id]);
return $stmt->fetch();
}
The problem was that the user did not have the correct privileges to access the database, after Your Common Sense suggested the creds were the issue, logged into MySQL cli and noticed the database was not in SHOW DATABASES.
Thanks for the help everybody.

Categories