is a right way manage transactions using static transactionCounter with multiple classes? - php

I'm interested in use the Database class described in http://php.net/manual/en/pdo.begintransaction.php
But that class has a problem, it uses a $transactionCount attribute that is not static, that means that if I have multiple classes beginning transactions it will cause multiple commits and will make my code finally go wrong, look this example (not runnable, simply for understand):
class Field extends Database {
public function createFieldToForm( $fieldName, $formId )
{
// static transactionCount = 0
// transactionCount = 0
$this->beginTransaction();
// .... createFieldToForm code ....
$last_id_new_fieldName = $this->insert( $fieldName );
$formFields = new FormFields();
$formFields->assignFieldToForm( $last_id_new_fieldName, $formId );
$this->commit();
}
public function insert( $fieldName )
{
try {
// static transactionCount = 1
// transactionCount = 1
$this->beginTransaction();
$dbh = Database::getDatabaseConnection();
$dbh->prepare( "INSERT INTO form(fieldname) VALUES (:fieldname)" );
// ... bind ...
$dbh->execute();
$this->commit();
return $dbh->lastInsertId();
}
catch (PDOException $e) {
$this->rollback();
}
}
}
class FormFields extends Database {
public function assignFieldToForm( $idFieldName, $formId )
{
// static transactionCount = 1
// transactionCount = 0
$this->beginTransaction();
// ... assign the created field to the form ....
$this->insert( $idFieldName, $formId );
$this->commit();
}
public function insert( $idFieldName, $formId )
{
try {
// static transactionCount = 2
// transactionCount = 1
$this->beginTransaction();
$dbh = Database::getDatabaseConnection();
$dbh->prepare( "INSERT INTO form_fields(idfield,formid) VALUES (:idfield,:formid)" );
// ... bind ...
$dbh->execute();
$this->commit();
}
catch (PDOException $e) {
$this->rollback();
}
}
}
const FORM_USER_INFORMATION = 3;
$fieldPhone = new Field();
$fieldPhone->createFieldToForm( "phone_number", FORM_USER_INFORMATION );
As you can see in the comments of this code the values of the $transactionCount is very different if it's static or not, but the main point of this question is about the static attribute, if is possible that its value could be changed by another code threads/functions or outside callings during the execution of (for example) createFieldToForm. What you can recommend to me to go ahead?

This class is not from the PHP manual but from the comments to the manual page. Which makes it deliberately unreliable source.
To solve your problem just get rid of all these "transactions". As it makes no sense to use a transaction for just a single query.
Therefore, most likely you don't need neither transactions, not counters, nor this class at all.

Related

Assign object attributes from the result of prepared statement

I'm wanting to create a new instance of my Class and assign it's attributes the values that are returned. The reason for this is I'm creating a series of methods inheriting from the calling class, as opposed to using static methods which I already had working.
Example of what I'm using currently:
public static function findById($id) {
$id = self::escapeParam($id);
$idVal = is_int($id) ? "i" : "s";
$sql = "SELECT * FROM ".static::$db_table." WHERE id = ? LIMIT 1";
return static::findByQuery($sql,$idVal,$id);
}
public static function findByQuery($sql,$bindChar = '',$bindVal = '') {
try {
$callingClass = get_called_class();
$object = new $callingClass;
$statement = Database::$connection->prepare($sql);
if(!empty($bindChar)) :
$statement->bind_param($bindChar, $bindVal);
endif;
if($statement->execute()) :
$result = $statement->get_result();
$object = $result->fetch_object();
endif;
$statement->close();
if(!empty($object)) :
return $object;
endif;
} catch(Exception $e) {
}
}
What I tried was writing an instantiation method that creates a new instance of my class, and then assign each attribute of the object the value it returns from an array from a tutorial I did. However, the tutorial was fairly outdated and didn't use any new syntax or binding, so I was trying to rework this.
Example from the tutorial below:
public static function find_by_id($id) {
global $database;
$the_result_array = static::find_by_query("SELECT * FROM " . static::$db_table . " WHERE id = $id LIMIT 1");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function find_by_query($sql) {
global $database;
$result_set = $database->query($sql);
$the_object_array = array();
while($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = static::instantation($row);
}
return $the_object_array;
}
public static function instantation($the_record){
$calling_class = get_called_class();
$the_object = new $calling_class;
foreach ($the_record as $the_attribute => $value) {
if($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
private function has_the_attribute($the_attribute) {
return property_exists($this, $the_attribute);
}
What I was trying to do from the tutorial, was to return my result as an array using a while, and then assigning a variable by passing the built array into the static::instantation() method, but it doesn't seem to ever be working correctly, as any public functions I create in my calling class (Admin for example) aren't called after as they don't exist due to the Class not being instantiated.
mysqli_result::fetch_object() accepts the class name as the first argument. You can pass the class name as an argument to that method and get the instance of the model. I am not sure why you have that much code but consider my example which I wrote based on your own code:
<?php
class Model
{
public static function findByQuery(string $sql, ?string $bindChar = null, ?string $bindVal = null): ?static
{
$statement = Database::$connection->prepare($sql);
if ($bindChar) :
$statement->bind_param($bindChar, $bindVal);
endif;
$statement->execute();
$result = $statement->get_result();
return $result->fetch_object(static::class);
}
}
class User extends Model
{
private $id;
}
class Database
{
public static mysqli $connection;
}
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Database::$connection = new mysqli('localhost', 'user', 'password', 'test');
$user = User::findByQuery('SELECT ? as id', 's', 'Dharman');
var_dump($user);
The output from that example is:
object(User)#4 (1) {
["id":"User":private]=>
string(7) "Dharman"
}
As you can see, the code created an instance of the class using late-static binding and it also assigned the value to a private property, which you can't do otherwise.
P.S. My example is a little bit tidier. I added parameter typing and removed a lot of unnecessary code. In particular, I remove empty try-catch which is a terrible practice.
I have now got this working, although I feel this is probably not the best way of doing it.
I'm primarily front end so please comment if there are improvements or best practices.
public static function findByQuery($sql,$bindChar = '',$bindVal = '') {
try {
$statement = Database::$connection->prepare($sql);
if(!empty($bindChar)) :
$statement->bind_param("$bindChar", $bindVal);
endif;
if($statement->execute()) :
$result = $statement->get_result();
$output = $result->fetch_object();
endif;
$statement->close();
if(!empty($output)) :
$class = get_called_class();
$object = new $class;
foreach(get_object_vars($output) as $key => $value) :
$object->$key = $value;
endforeach;
endif;
if(!empty($object)) :
return $object;
endif;
} catch(Exception $e) {
}
}
My initial thoughts were declaring an object and then I thought that the PHP fetch_object call would have just assigned my object it's properties after initiating the Class but that wasn't the case.
So what I've done is that if the statement is successful and a results object is created, I then get the object properties and values with the get_object_vars() command, and then loop through these as a key value pair, assigning each attribute it's returned value.
I can confirm this works as I can now run $admin->remove() from my removal script, as opposed to what I was having to do before which was Admin::remove($id);

Declaring new class() beginning of class

I'm working on a Content Management System for My wife who wants to create a website, and I have a way I've always done things within the past, but I want to deliver better coding procedures, so this is my dilemma.
This is Code I've used in the past that I know works.
class accounts {
public function CheckAccountLogin() {
global $db;
$query = <<<SQL
SELECT id,gaToken
FROM accounts
WHERE password_hash = :hashedpw
SQL;
$resource = $db->sitedb->prepare( $query );
try {
$resource->execute( array (
':hashedpw' => sha1($_POST['user-name'].':'.$_POST['user-pass']),
));
if($resource->rowCount() == 0 ) { echo false;}
else {
foreach($resource as $row) {
$this->authkey = $row['gaToken'];
if($this->authkey == "") {
self::SetSession();
}
else {
self::CheckAuth();
}
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
Now every function would need global $db at the start of the function in order to utilize $db->sitedb or else we would have an error thrown our way, so what I want to do instead is
class accounts {
public $db = new db();
public function CheckAccountLogin() {
$query = <<<SQL
SELECT id,gaToken
FROM accounts
WHERE password_hash = :hashedpw
SQL;
$resource = $this->sitedb->prepare( $query );
try {
$resource->execute( array (
':hashedpw' => sha1($_POST['user-name'].':'.$_POST['user-pass']),
));
if($resource->rowCount() == 0 ) { echo false;}
else {
foreach($resource as $row) {
$this->authkey = $row['gaToken'];
if($this->authkey == "") {
self::SetSession();
}
else {
self::CheckAuth();
}
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
This way within all my new functions I'm able to simply declare $this->sitedb whenever I need to connect to the database. With the above code I'm given
Parse error: syntax error, unexpected 'new' (T_NEW) in /var/www/html/functions.d/accounts.class.php on line 3. I know where the issue is, I'm just looking for a cleaner way than my first code block. Any help in getting this to work correctly would be greatly appreciated.
You can't initialize a variable there unless it can be evaluated at compile time. So you can't call new there. See the docs. Do it in the constructor.
class accounts {
public $db;
public function __construct() {
$this->db = new db();
}
}
You can create a global class DbConnect where you statically define the database object db and connect it to your database, in this way you will keep a single database connection object throughout your application.
Include this class at the beginning before any code, then you can access this object anywhere through :: operator in any class that follows.

PHP variables not getting overwritten on subsequent queries

The Situation
I'm fairly new to object-oriented programming in PHP and currently I'm creating a small CMS for learning purposes. I've learned a lot about OOP on my way, but I'm facing a weird issue at the moment. I've created a Singleton class to deal with the database connection and queries.
public static function getInstance()
{
if(!isset(self::$instance))
{
self::$instance = new Database();
}
return self::$instance;
}
In the same class, there also is a method to execute queries. It takes two parameters, the query and an optional array with parameters to bind for the prepared statements. You can see its source below.
public function execute($query, $params = array())
{
$this->error = false; // Set 'error' to false at the start of each query.
if($this->query = $this->pdo->prepare($query))
{
if(!empty($params))
{
$index = 1;
foreach($params as $parameter)
{
$this->query->bindValue($index, $parameter);
++$index;
}
}
if($this->query->execute())
{
$this->results = $this->query->fetchAll(PDO::FETCH_OBJ);
$this->count = $this->query->rowCount();
}
else
{
$this->error = true;
}
}
return $this;
}
The Problem
If I have multiple queries on the same page, the results and count variables still contain the values of the first query. Imagine the following - the first query retrieves all users from my database. Let's say there are 15. The second query retrieves all blog posts from the database, let's say there are none. If no posts are present, I want to display a message, otherwise I run a loop to display all results. In this case, the loop is executed even though there are no blog posts, because the count variable is used to determine if there are posts in the database and it still holds the 15 from the first query somehow.
This obviously leads to some errors. Same with results. It still holds the value from the first query.
$query = Database::getInstance()->execute('SELECT * FROM articles ORDER BY article_id DESC');
if(!$query->countRes())
{
echo '<h2>There are no blog posts in the database.</h2>';
}
else
{
foreach($query->results() as $query)
{
echo '<article>
<h3>'.$query->article_heading.'</h3>
<p>'.$query->article_preview.'</p>
</article>';
}
}
The countRes() and results() methods simply return the variables from the DB class.
I hope that I have explained the problem understandable. Responses are very appreciated.
I would use a response object to avoid attaching query specific data to the global database object.
Example:
<?php
class PDO_Response {
protected $count;
protected $results;
protected $query;
protected $error;
protected $success = true;
public function __construct($query){
$this->query = $query;
try{
$this->query->execute();
}catch(PDOException $e){
$this->error = $e;
$this->success = false;
}
return $this;
}
public function getCount(){
if( is_null( $this->count ) ){
$this->count = $this->query->rowCount();
}
return $this->count;
}
public function getResults(){
if( is_null( $this->results ) ){
$this->results = $this->query->fetchAll(PDO::FETCH_OBJ);
}
return $this->results;
}
public function success(){
return $this->success;
}
public function getError(){
return $this->error;
}
}
Then in your database class:
public function execute($query, $params = array())
{
if($this -> _query = $this -> _pdo -> prepare($query))
{
if(!empty($params))
{
$index = 1;
foreach($params as $parameter)
{
$this -> _query -> bindValue($index, $parameter);
++$index;
}
}
return new PDO_Response($this->_query);
}
throw new Exception('Some error text here');
}
UPDATE: Moved execution into response class for error handling
Example usage (not tested)
$select = $database->execute('SELECT * FROM table');
if( $select->success() ){
//query succeeded - do what you want with the response
//SELECT
$results = $select->getResults();
}
$update = $database->execute('UPDATE table SET col = "value"');
if( $update->success() ){
//cool, the update worked
}
This will help fix your issue in the event that subsequent queries fail, there will not be any old query data attached to the database object.

PHP function inside a class function include

I am working with lemonade-php. My code is at https://github.com/sofadesign/limonade.
The issue I am having is when I try to run
class syscore {
public function hello(){
set('post_url', params(0));
include("./templates/{$this->temp}/fullwidth.tpl");
return render('fullwidth');
}
}
which then loads the fullwidth.tpl and runs function fullwidth
fullwidth.tpl
<?php
global $post;
function fullwidth($vars){
extract($vars);
$post = h($post_url);
}
print_r($this->post($post));
?>
it seems to pass the $post_url but I can not pass it again to the print_r($this->post($post));
However when I try to run print_r($this->post($post)) inside the fullwidth function it says it can not find the post() function
I have tried a number of things like below
function fullwidth($vars){
extract($vars);
$post = h($post_url);
print_r(post($post));
}
I tried re connecting to the syscore by
$redi = new syscore();
$redi->connection() <-- this works
$redi->post($post) <-- this does not
Here is my full class syscore
class syscore {
// connect
public function connect($siteDBUserName,$siteDBPass,$siteDBURL,$siteDBPort, $siteDB,$siteTemp){
for ($i=0; $i<1000; $i++) {
$m = new Mongo("mongodb://{$siteDBUserName}:{$siteDBPass}#{$siteDBURL}:{$siteDBPort}", array("persist" => "x", "db"=>$siteDB));
}
// select a database
$this->db = $m->$siteDB;
$this->temp = $siteTemp;
}
public function hello(){
set('post_url', params(0));
include("./templates/{$this->temp}/fullwidth.tpl");
return render('fullwidth');
}
public function menu($data)
{
$this->data = $data;
$collection = $this->db->redi_link;
// find everything in the collection
//print $PASSWORD;
$cursor = $collection->find(array("link_active"=> "1"));
if ($cursor->count() > 0)
{
$fetchmenu = array();
// iterate through the results
while( $cursor->hasNext() ) {
$fetchmenu[] = ($cursor->getNext());
}
return $fetchmenu;
}
else
{
var_dump($this->db->lastError());
}
}
public function post($data)
{
$this->data = $data;
$collection = $this->db->redi_posts;
// find everything in the collection
//print $PASSWORD;
$cursor = $collection->find(array("post_link"=> $data));
if ($cursor->count() > 0)
{
$posts = array();
// iterate through the results
while( $cursor->hasNext() ) {
$posts[] = ($cursor->getNext());
}
return $posts;
}
else
{
var_dump($this->db->lastError());
}
}
}
It looks like you are having some issues understanding the execution path that PHP is taking when trying to render your template. Let's take a more in-depth look, shall we?
// We're going to call "syscore::hello" which will include a template and try to render it
public function hello(){
set('post_url', params(0)); // set locals for template
include("./templates/{$this->temp}/fullwidth.tpl"); // include the template
return render('fullwidth'); // Call fullwidth(array('post_url' => 'http://example.com/path'))
}
The trick to solving this one is to understand how PHP include works. When you call include("./templates/{$this->temp}/fullwidth.tpl") some of your code is executing in the scope of the syscore object, namely:
global $post;
and
print_r($this->post($post));
fullwidth is created in the global scope at this point, but has not yet been called. When render calls fullwidth you're no longer in the syscore scope, which is why you cannot put $this->post($post) inside without triggering an error.
Ok, so how do we solve it? Glad you asked.
We could probably refactor syscore::post to be a static method, but that would then require syscore::db to be static, and always return the SAME mongodb instance (singleton pattern). You definitely do not want to be creating 1000 Mongo instances for each syscore instance.
We could just abuse the framework. A much poorer solution, but it will get the job done.
fullwidth.tpl
<?php
function fullwidth($vars){
$post_url = ''; // put the variables you expect into the symbol table
extract($vars, EXTR_IF_EXISTS); // set EXTR_IF_EXISTS so you control what is added.
$syscore_inst = new syscore;
$post = h($post_url);
print_r($syscore->post($post)); // I think a puppy just died.
}
Look the second way is a complete hack, and writing code like that will probably mean you won't get promoted. But it should work.
But let's say you wanted to get promoted, you would make good, shiny code.
// Note: Capitalized class name
class Syscore {
protected static $_db;
public static function db () {
if (! static::$_db) {
static::$_db = new Mongo(...);
}
return static::$_db;
}
// #FIXME rename to something more useful like "find_posts_with_link"
public static post($url) {
$collection = static::db()->redi_posts;
// find everything in the collection
$cursor = $collection->find(array("post_link"=> $url));
// Changed to a try-catch, since we shouldn't presume an empty find is
// an error.
try {
$posts = array();
// iterate through the results
while( $cursor->hasNext() ) {
$posts[] = ($cursor->getNext());
}
return $posts;
} catch (Exception $e) {
var_dump($this->db->lastError());
}
}
}
Then in your fullwidth function, we don't have to do any of that stupid nonsense of treating an instance method like it were a static method.
function fullwidth($vars){
$post_url = ''; // put the variables you expect into the symbol table
extract($vars, EXTR_IF_EXISTS); // set EXTR_IF_EXISTS so you control what is added.
$post = h($post_url);
print_r(Syscore::post($post)); // static method. \O/ Rainbows and unicorns.
}

PDO use in multiple functions - reuse of prepared statement

I have a class "test" with 2 functions, one to create the prepared statement and one to execute one or more times. The problem is how do i set the binding in the first one and fill in the vars on the other function.
class test {
private static $moduleSql = "SELECT
id,
module
FROM
phs_pages
WHERE
prettyurl = :prettyUrl AND
mainId = :mainId
";
private static function pre() {
$db = Db_Db::getInstance();
self::$preModuleSql = $db->prepare(self::$moduleSql);
self::$preModuleSql->bindParam(':prettyUrl', $prettyUrl);
self::$preModuleSql->bindParam(':mainId', $mainId);
}
private static function getClassByDb($mainId = 0, $id = 0) {
$prettyUrl = self::$parts[$id];
self::$preModuleSql->execute();
self::$preModuleSql->debugDumpParams();
$result = self::$preModuleSql->fetch(PDO::FETCH_ASSOC);
// get lower level classes
if (isset(self::$parts[$id + 1])) {
self::getClassByDb($result['id'], $id + 1);
} else {
return $result;
}
}
}
You donĀ“t need to bind any parameters in your first function, you need to do that in your second function, right before you execute the prepared statement.
Edit: By the way, you can also call execute with an array that contains your parameters as keys and the values you want to send.
There are so many things wrong with this class definition .. ehh.
It should look like this :
class RepositoryException extends Exception{}
interface iRepository
{
public function store( $key , PDOStatement $statement );
public function fetch( $key );
}
class StatementRepository implements iRepository{
protected $_pool = array();
public function store( $key , PDOStatement $statement )
{
$this->_pool[ $key ] = $statement;
}
public function fetch( $key )
{
if ( !array_key_exists( $key , $this->_pool ) ){
throw new RepositoryException(
"Statement with name '$key' does not exist" );
}
return $this->_pool[ $key ];
}
}
$repo = new StatementRepository;
$foo = new Foo( $repo );
$bar = new Bar( $repo );
$db = new PDO('sqlite::memory:');
$statement = $db->prepare( 'SELECT .... ');
$repo->store( 'bljum' , $statement );
This way all the object which have accepted in the constructor an object which implements iRepository can fetch statements by name.
You class should not have more responsibilities then it needs. If it is for storing prepared statements , then it should have nothing to do with binding parameters to them and executing something.
Here is what Foo class would do :
class Foo
{
protected $_repo = null;
public function __construct( iRepository $repo )
{
$this->_repo = $repo;
}
public function ergo( $x , $y )
{
$statement = $this->_repo->fetch('bljum');
//bind values
$statement->execute();
}
}

Categories