Prepared statement PHP OOP - php

Working on a product adding page using PHP OOP and mysqli, at this point i'm working on prepared statement implementation but can't find information on how to add them into such code.
Any guidlines will be apreciated.
Code:
DB connection class:
<?php
class DbConfig {
private $_host = 'localhost';
private $_username = 'root';
private $_password = 'falcons17';
private $_database = 'scandiweb';
protected $connection;
public function __construct()
{
if (!isset($this->connection)) {
$this->connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);
if (!$this->connection) {
echo 'Cannot connect to database server';
exit;
}
}
return $this->connection;
}
}
?>
Execute function:
public function execute($query) {
$result = $this->connection->query($query);
if ($result == false) {
echo mysqli_error($this->connection); /*'Error: cannot execute the command'*/
return false;
} else {
return true;
}
}
Validating and adding procedure :
<?php
//including the database connection file
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['Submit'])) {
$sku = $crud->prepare_string($_POST['sku']);
$name = $crud->prepare_string($_POST['name']);
$price = $crud->prepare_string($_POST['price']);
$products = $crud->prepare_string($_POST['products']);
$weight = $crud->prepare_string($_POST['weight']);
$capacity = $crud->prepare_string($_POST['capacity']);
$height = $crud->prepare_string($_POST['height']);
$width = $crud->prepare_string($_POST['width']);
$length = $crud->prepare_string($_POST['length']);
$check_int = $validation->is_int($_POST, array('price','weight','capacity','height','width','length'));
if ($check_int != null){
echo $check_int;
}else {
$result = $crud->execute("INSERT INTO products(sku,name,price,product_type,weight,capacity,height,width,length) VALUES('$sku','$name','$price','$products','$weight','$capacity','$height','$width','$length')");
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>

Here is a class i often use. It gets the login from a separate .ini-file. Feel free to change for your needs. Keep in mind that it sets associative arrays as standard.
class CC_DBV {
private static $mysqlhost;
private static $mysqluser;
private static $mysqlpwd;
public static $mysqldb;
private static $db;
private static $mysqlport;
function __construct() {
// ini File einlesen
$globSettings = parse_ini_file(_ROOTV_.'cfg/main.ini',true);
// Datenbankverbindung
self::$mysqlhost = $globSettings ['db_settings']['host']; // MySQL-Host aus Config Datei
self::$mysqluser = $globSettings ['db_settings']['db_user']; // MySQL-User aus Config Datei
self::$mysqlpwd = $globSettings ['db_settings']['db_pswd']; // Passwort aus Config Datei
self::$mysqldb = $globSettings ['db_settings']['db']; // Datenbank aus Config Datei
self::$mysqlport = $globSettings ['db_settings']['port']; // Datenbank aus Config Datei
}
public function getInstance( ) {
if(!self::$db) {
try{
self::$db = new \PDO(
'mysql:host='.self::$mysqlhost.';dbname='.self::$mysqldb.';port='.self::$mysqlport,
self::$mysqluser,
self::$mysqlpwd,
array(
\PDO::ATTR_PERSISTENT => true,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"
)
);
//self::$db->exec("SET NAMES utf8");
return self::$db;
}catch (\PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}else{
return self::$db;
}
}
}
To use it you do something like this:
$conn = new CC_DBV(); // you can use this connection multiple times, it's persistant.
$inst = $conn->getInstance(); // create or get the instance of the opened connection
$stmnt = $inst->prepare("SELECT * FROM tablename WHERE xyz = :VAR1"); // prepare statement with placeholder(s)
$v = array(':VAR1' => 'aValue'); // set up an array with corresponding values
$r1 = $stmnt->execute($v); // execute statement with values
if(!$r1){ echo "PANICMODE";}else{ var_dump($stmnt->fetchAll()));

Related

PHP script not receiving data

I have been looking at several php codes trying to find out the problem with my code, and why it wont receive data from post
below is my php code can any one tell me whats up with it
i am trying to send audio data with the name of the audio file through this php file
the php script is supposed to receive the audio file create then audio object and then extract the name and audio part from the file but when i send the data to test it through postman i get 400 error message as i have set it up to indicate error but i do not understand why this is happening
<?php
include_once '../../configration/database.php';
include_once '../../objects/sound.php';
// JWT TOKEN VALIDATION
$data = json_decode(file_get_contents("php://input"));
$database = new Database();
$conn = $database->getConnection();
// CONTROL
$sound = new Sound($conn);
// make sure data is not empty
if (
!is_null($data->$filename)
&& !is_null($data->$extension)
&& !is_null($data->$waveform) )
{
$sound->filename = $data->filename;
$sound->extension = $data->extension;
$sound->waveform = $data->waveform;
// create the product
if ($sound->create_new())
{
http_response_code(200);
}
else
{
http_response_code(503);
echo json_encode(array(
"message" => "Unable to create sound."
));
}
}
else {
http_response_code(400);
echo json_encode(array(
"message" => "Unable to create sound. Data is incomplete."
));
}
?>
the database.php file is as follows
<?php
include_once 'GlobalConfig.php';
class Database
{
public $conn;
public function getConnection(){
$config= new GlobalConfig();
$this->conn = null;
try{
$dsn = "mysql:host={$config->host};port={$config->port};dbname={$config->db_name};charset=utf8";
$this->conn = new PDO($dsn, $config->username, $config->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
public function getConnectionAndValidate($data){
$this->conn = null;
$config= new GlobalConfig();
try{
$dsn = "mysql:host={$config->host};port={$config->port};dbname={$config->db_name};charset=utf8";
$this->conn = new PDO($dsn, $config->username, $config->password);
$this->conn->exec("set names utf8");
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
if (!validateToken($data->JWT, $data->UserID, $this->conn)){
http_response_code(401);
echo "Authorization: declined";
exit();
}
return $this->conn;
}
}
THE sound.php FILE IS AS FOLLOWS
<?php
class Sound
{
private $conn;
private $table_name = "";
public $filename;
public $extension;
public $waveform;
public $path;
public function __construct($db)
{
$this->conn = $db;
}
function create_new()
{
$this->path = $this->filename .".". $this->extension;
$myfile = fopen($this->path, "w") or die("Unable to open file!");
fwrite($myfile, $this->waveform);
fclose($myfile);
// $query = " INSERT INTO `tbl_address`
// (`contact_number`,`UserID` ,`billing_street_address`, `billing_city_address`, `billing_state_address`, `billing_country_address`, `billing_zip`,
// `shipping_street_address`, `shipping_city_address`, `shipping_state_address`, `shipping_country_address`, `shipping_zip`)
// VALUES (:contact_number,'$this->user_id', :billing_street_address, :billing_city_address, :billing_state_address, :billing_country_address, :billing_zip,
// :shipping_street_address, :shipping_city_address, :shipping_state_address, :shipping_country_address, :shipping_zip);";
// $stmt = $this->conn->prepare($query);
// $this->contact_number = htmlspecialchars(strip_tags($this->contact_number));
// $this->billing_street_address = htmlspecialchars(strip_tags($this->billing_street_address));
// $this->billing_city_address = htmlspecialchars(strip_tags($this->billing_city_address));
// $this->billing_state_address = htmlspecialchars(strip_tags($this->billing_state_address));
// $this->billing_country_address = htmlspecialchars(strip_tags($this->billing_country_address));
// $this->billing_zip = htmlspecialchars(strip_tags($this->billing_zip));
// $this->shipping_street_address = htmlspecialchars(strip_tags($this->shipping_street_address));
// $this->shipping_city_address = htmlspecialchars(strip_tags($this->shipping_city_address));
// $this->shipping_state_address = htmlspecialchars(strip_tags($this->shipping_state_address));
// $this->shipping_country_address = htmlspecialchars(strip_tags($this->shipping_country_address));
// $this->shipping_zip = htmlspecialchars(strip_tags($this->shipping_zip));
// // bind values
// $stmt->bindParam(":contact_number", $this->contact_number);
// $stmt->bindParam(":billing_street_address", $this->billing_street_address);
// $stmt->bindParam(":billing_city_address", $this->billing_city_address);
// $stmt->bindParam(":billing_state_address", $this->billing_state_address);
// $stmt->bindParam(":billing_country_address", $this->billing_country_address);
// $stmt->bindParam(":billing_zip", $this->billing_zip);
// $stmt->bindParam(":shipping_street_address", $this->shipping_street_address);
// $stmt->bindParam(":shipping_city_address", $this->shipping_city_address);
// $stmt->bindParam(":shipping_state_address", $this->shipping_state_address);
// $stmt->bindParam(":shipping_country_address", $this->shipping_country_address);
// $stmt->bindParam(":shipping_zip", $this->shipping_zip);
// if ($stmt->execute()) {
// $this->address_id = $this->conn->lastInsertId();
// }
// else {
// echo json_encode(array("message" => "Unable to get address."));
// }
}
}
?>

pdo disconnect from database in class

I wrote a class for PDO and need to disconnect PDO => ( I don't know how to do it )
I don't know code wrote is structurally correct?!
use $this->returnconn(); for db connection
Please guide me...
Sample code:
class conn {
public $inner;
public function returnconn() {
$CONF = $TMPL = array();
// The MySQL credentials
$CONF['host'] = 'localhost';
$CONF['user'] = 'root';
$CONF['pass'] = '';
$CONF['name'] = 'cmss';
$dsn ="mysql:host=".$CONF['host'].";dbname=".$CONF['name']."";
try{
$conn = new PDO($dsn,$CONF['user'],$CONF['pass']);
$conn ->exec("SET CHARACTER SET UTF8");
}catch(PDOException $e){
die($e->getMessage());
}
return $conn;
}
public function select(){
switch ($this->inner->switch){
case "select":
$sql="SELECT ".$this->inner->todo." FROM ".$this->inner->table." WHERE ".$this->inner->sql."";
$result=$this->returnconn()->prepare($sql);
/*
* this->returnconn();
*/
$result->execute();
if($result->rowCount()<=0){
return '{"msg":"empty "}';
}else{
return $result->fetch(PDO::FETCH_ASSOC);
}
break;
}
}
}
/* receive data */
$obj = new conn;
$iner = array();
$iner['table'] = 'category';
$iner['switch'] ='select';
$iner['todo'] = '*';
$iner['sql'] = '`id` IS NOT NULL ORDER BY `id` ASC';
$in = json_decode(json_encode($iner));
$obj ->inner = $in;
echo json_encode($obj ->select());
Do need a function to disconnect?

Fixing max_user_connections in PHP class using PDO

I have been adapting an older abstraction layer to use PDO but I am running into user x has more than 'max_user_connections' active connections SQLSTATE[HY000] [1203] errors when looping through large sets. I have been reading on http://php.net/manual/en/pdo.connections.php but all of my attempts to unset the $dbh from within the loops result in errors from having ended the connection.
Base class looks like
class DB {
public $pdo;
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
public function __construct()
{
$this->connect();
}
private function connect()
{
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8;", $this->user, $this->pass, $options);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
public function __destruct()
{
$this->connection = null;
$this->pdo = null;
unset($this->pdo);
}
// CRUD methods follow including
function retrieve($where, $groupBy='', $order_by='') {
$query = "SELECT * FROM `$this->table` $where $groupBy $order_by";
$q = $this->pdo->prepare($query);
$q->execute();
$result = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,get_class($this));
// was $result = $q->fetchAll(PDO::FETCH_CLASS,get_class($this));
$this->query_log($query);
$q = null;
if ($result == 'NULL') {
return false;
} else {
return $result;
}
} // retrieve()
And an example that has the errors would be
if (in_array($_GET['type'], $types)) {
$type = $_GET['type'];
$rsObj = new ReservedSlug;
if ($type == 'artist') {
$obj = new CalendarArtist;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'event') {
$obj = new CalendarEvent;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'location') {
$obj = new Location;
$slugfield = 'UrlSlug';
$namefield = 'LocationName1';
}
$needslug = $obj->retrieve("TRIM(`$namefield`) != '' AND (`$slugfield` = '' OR `$slugfield` IS NULL) LIMIT 0,400");
if ($needslug) {
foreach ($needslug as $ns) {
$testslug = slugify($ns->$namefield);
list($reserved) = $rsObj->retrieve("`slug` = '$testslug' AND `type` = '$type'");
if (!$reserved) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug'");
if ($test) {
for ($i = 2; $i < 26; $i++) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug-$i'");
if (!$test) {
$slug = $testslug . '-' . $i;
}
}
} else { // not found in table
$slug = $testslug;
}
} else { // was reserved
$slug = false;
}
echo $ns->$namefield . " gets $slug<p>";
} // foreach needslug
} // if needslug
} // type found in array
So I need to understand how to not create new connections when an active connection is available and how to properly __destruct() these child objects. Where am I going wrong?

DB class wont load

I'm trying to connect using a simle db class. For some reason it only print out
"Initiate DB class"
test.php
include 'db.class.php';
echo 'Initiate DB class';
$db = new DB();
echo 'DB class did load';
db.class.php
class DB extends mysqli {
private static $instance = null;
private function __construct () {
parent::init();
$host = 'localhost';
$user = 'root';
$pass = 'MY_PASS';
$dbse = 'MY_DB';
parent::real_connect($host, $user, $pass, $dbse);
if (0 !== $this->connect_errno):
die('MySQL Error: '. mysqli_connect_error());
//throw new Exception('MySQL Error: '. mysqli_connect_error());
endif;
}
public function fetch ($sql, $id = null, $one = false) {
$retval = array();
if ($res = $this->query($sql)):
$index = 0;
while ($rs = $res->fetch_assoc()):
if ($one):
$retval = $rs; break;
else:
$retval[$id ? $rs[$id] : $index++] = $rs;
endif;
endwhile;
$res->close();
endif;
return $retval;
}
}
I have tried to search my log files for error but they come out empty.
Ok got it,
In your call to db your calling new DB(); which mean you're trying to call the constructor of your DB class.
In your DB class it looks like you're trying to create a singleton, but something is missing normally there would be something to assign the instance the database connection, and something that asks the instance if it's empty create a new connection or if it's not use the same instance.
At the end of the day to make this work you can change your constructor to public.
Try this:
Db_class:
class Db_class{
/***********************CONNECT TO DB*********************/
public function db_connect(){
$user = '***';
$db = '***';
$password = '***';
$host = '***';
try {
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $password);
}
catch(PDOException $err) {
echo "Error: ".$err->getMessage()."<br/>";
die();
}
return $dbh;
}
/******************PREPARE AND EXECUTE SQL STATEMENTS*****/
public function query($statement){
$keyword = substr(strtoupper($statement), 0, strpos($statement, " "));
$dbh = $this->db_connect();
if($dbh){
try{
$sql = $dbh->prepare($statement);
$exe = $sql->execute();
}
catch(PDOException $err){
return $err->getMessage();
}
switch($keyword){
case "SELECT":
$result = array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$result[] = $row;
}
return $result;
break;
default:
return $exe;
break;
}
}
else{
return false;
}
}
Other PHP:
$db = new Db_class();
$sql = "SQL STATEMENT";
$result = $db->query($sql);
Your constructor is marked as private which means new DB will raise an error. I see you have a private property to store an instance, are you missing the singleton method to return a new object?

Update PHP class from mssql_ to sqlsrv_

We've just updated PHP on our server, for the most part everything is fine, but the mssql_ functions aren't supported any more unfortunately. I've tried to update our previous class:
$connection['server'] = 'server, port';
$connection['user'] = 'user';
$connection['pass'] = 'pass';
$connection['db'] = 'db';
class mssqlClass {
function connect($dbhost = NULL){
global $connection;
if(! ISSET ($dbconnect)){
$dbconnect = mssql_Connect($connection['server'], $connection['user'], $connection['pass'], true);
}
if(! $dbconnect){
return 'Failed to Connect to Host';
}else{
$select = mssql_select_db($connection['db'], $dbconnect);
if(! $select){
return 'Failed to select Database';
}else{
return $dbconnect;
}
}
}
function getData ($query){
$this->data_array = array();
$result = mssql_query($query);
while ($row = mssql_fetch_assoc($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query){
$result = mssql_query($query) or die("Query didn't work");
}
}
To be compliant with sqlsrv_, and whilst I can connect to the database without any issues, it won't return any data!:
class mssqlClass {
function connect($database = 'Db') {
$mssql_server = 'server';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
if(! ISSET ($dbconnect)){
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
}
if(! $dbconnect){
return 'Failed to connect to host';
}
}
function getData ($query) {
$result = sqlsrv_query($db->connect, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
}
ps. Example usage is as follows:
$db = new mssqlClass();
$conn = $db->connect('DATABASE');
$query = "SELECT * FROM Table";
$result= $db->getData($query);
So sorry for the horrible amount of code - I can edit it down to just the getData function if that's easier? Thank you!!
I've made some changes in your class:
<?php
class mssqlClass {
protected $connection = null;
public function connect($database = 'Db') {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
// data for making connection
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
// try to connect
$this->connection = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
}
public function getData ($query) {
// reset results; is this really needed as object's variable? Can't it be just local function's variable??
$this->data_array = array();
$result = $this->query($this->connection, $query);
while ($row = sqlsrv_fetch_array($result)) {
$this->data_array[] = $row;
}
return $this->data_array;
}
public function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work..");
}
}
The code looks fine. The only thing which could be your problem is that sqlsrv_fetch_array needs maybe a second parameter e.g.:
sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)
Because the default is that it returns two arrays with different formats. And if you may acess attributes by name it will return nothing but not fail.
Something like this. Because you actually call the sqlsrv_query method with the return value of the following method. And in the original version you missed to return the connection resource.
function connect($database = 'Db') {
$mssql_server = 'gc-hr01';
$mssql_data = array("UID" => 'uid',
"PWD" => 'pwd',
"Database" => $database);
$dbconnect = sqlsrv_connect($mssql_server, $mssql_data);
if(! $dbconnect){
return 'Failed to connect to host';
}
return $dbconnect;
}
in advance
function getData ($query) {
$result = sqlsrv_query($db->connect(), $query);
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$this->data_array[] = $row;
}
$m = $this->data_array;
return $m;
}
function query($query) {
$result = sqlsrv_query($query) or die("Query didn't work.");
}
I found this page while trying to find a quick short-cut to someone else's wrapper class for sqlsrv commands. Since this wasn't really complete, I have compiled my own quickly. Please don't think this is production code, you should test and test again, but it might help someone out of a jam quickly.
class db {
protected $connection = null;
private $debug = true;
private $stmt = null;
private $insertid = null;
private $affectedrows = null;
public function db($host = '.',$database,$username,$password) {
// we don't need to connect twice
if ( $this->connection ) {
return;
}
sqlsrv_configure('WarningsReturnAsErrors', 0);
// data for making connection
$sqlsvr_details = array( 'UID' => $username,
'PWD' => $password,
'Database' => $database,
'CharacterSet' => 'UTF-8'
);
// try to connect
$this->connection = sqlsrv_connect($host, $sqlsvr_details);
if($this->connection == false){
$this->debug('Failed to connect to host: '.$this->errors(),true);
return false;
}else{
return true;
}
}
public function query($query) {
return new resultset($query,$this->connection,$this->debug);
}
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
public function delete($query){
return $this->update($query);
}
public function update($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
$this->affectedrows = #sqlsrv_rows_affected($this->stmt);
return $this;
}
}
public function insert($query){
//Not happy with this
$this->affectedrows = null;
$this->insertid = null;
$this->stmt = sqlsrv_query($this->connection, $query);
if (!$this->stmt){
$this->debug('SQL Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
//Get the last insert ID and store it on here
$this->insertid = $this->query('select ##IDENTITY as insert_id')->asObject()->insert_id;
return $this;
}
}
public function insert_id(){
return $this->insertid;
}
public function affected_rows(){
return $this->affectedrows;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}
class resultset implements Countable,Iterator {
private $result = null;
private $connection = null;
private $debug = false;
private $internal_pointer = 0;
private $data = array();
public function resultset($query,$link,$debug = false){
$this->connection = $link;
$this->debug = $debug;
$this->result = sqlsrv_query($this->connection, $query, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC));
if ($this->result == false){
$this->debug('Query Failed: '.$query.' '.$this->errors(),true);
return false;
}else{
return $this;
}
}
public function asObject($step = true){
$object = sqlsrv_fetch_object($this->result,NULL,NULL,SQLSRV_SCROLL_ABSOLUTE,$this->internal_pointer);
if (! $object){
return false;
}else{
if ($step) $this->internal_pointer++;
return $object;
}
}
public function num_rows() {
return sqlsrv_num_rows($this->result);
}
public function free(){
$this->internal_pointer = 0;
if (is_resource($this->result)){
sqlsrv_free_stmt($this->result);
}
}
public function __destory(){
$this->free();
}
//Countable Function
public function count(){
return $this->num_rows();
}
//Iteration Functions
public function rewind(){
$this->internal_pointer = 0;
}
public function current(){
return $this->asObject(false);
}
public function key(){
return $this->internal_pointer;
}
public function next(){
$this->internal_pointer++;
}
public function valid(){
return $this->internal_pointer <= $this->num_rows();
}
//============================================
private function debug ($message,$hard = false){
if ($this->debug){
if ($hard){
die($message);
}else{
echo $message;
}
}
return true;
}
private function errors(){
return print_r( sqlsrv_errors(SQLSRV_ERR_ERRORS), true);
}
}

Categories