September 9, 2013

How to Get Parameters from Database in PHP with PDO

M4g4bu’s Question:

I’m developing a setup class to manage some parameters stored in the database and I am trying to make a class effective and shorter so, I did this:

First, I add a db.php file where the database is configured and connected, after that I added the parameters as private attributes. To process them in a better way all are included into an Array, so I build the query in the variable ‘consulta’ processing the information and retrieve one by one the values from the db

<?php
  require 'db.php';

  class setup {
private $lenguaje;
private $charset;
private $sitio_titulo;
private $sitio_descripcion;
private $kewords;
private $autor;
private $path_css_frontend;
private $path_css_backend;
private $path_modernizr;
private $path_jquery;
private $logo_url;
private $copyright;
private $dbconn;
private $site_version;

//edit – code separated only for visibility, part of same class

    public function __construct() {
    $this->dbconn = new database ();
}
private function fillData() {
    $valores = array (
            lenguaje,
            charset,
            sitio_titulo,
            sitio_descripcion,
            kewords,
            autor,
            path_css_frontend,
            path_css_backend,
            path_modernizr,
            path_jquery,
            logo_url,
            copyright,
            dbconn,
            site_version
    );
    $this->getData($valores);
}

//edit – code separated only for visibility, part of same class

public function getData($columnName) {

    while($columnName){

        $consulta = 'SELECT $columnName from config LIMIT 1';

        $this->dbconn->query ( $consulta );

        $this->dbconn->execute ();

        $r = $this->dbconn->fetch (); //

        '$this->'.$columnName = $r;

    }

   }

    ?>

did I something wrong?

First quote the values of your array or they will be considered as constants.

$valores = array (
            'lenguaje',
            'charset',
            'sitio_titulo',
            'sitio_descripcion',
            'kewords',
            'autor',
            'path_css_frontend',
            'path_css_backend',
            'path_modernizr',
            'path_jquery',
            'logo_url',
            'copyright',
            'dbconn',
            'site_version'
    );

Next, the way you are using while loop is wrong. Combine the array values and send one query.

public function getData($columnName) {

    $columnName = implode(",", $columnName);
    $consulta = 'SELECT $columnName from config LIMIT 1';

    // Query Now

}
April 24, 2012

php create objects from list of class files

Question by ing. Michal Hudak

I have directory CLASSES with files in my project.

../classes/class.system.php
../classes/class.database.php
...

I pull out every class and include it to main index.php with this code:

// load classes
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
}

and then I create (manually write) objects for example:

$system = new System();
$database = new Database();
...

Q: How can I automatically generate object for each class from list of files in directory CLASSES without writing them?

Thank you for your answers and code.

EDIT:

My working solution:

// load classes
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
    $t = explode(".",$filename);
    $obj = strtolower($t[1]);
    $class = ucfirst($t[1]);
    ${$obj} = new $class();
}

Answer by ing. Michal Hudak

// load classes and create objects
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
    $t = explode(".",$filename);
    $obj = strtolower($t[1]);
    $class = ucfirst($t[1]);
    // create object for every class
    ${$obj} = new $class();
}

Answer by Starx

IF you follow a typical pattern, while creating those files like

class.<classname>.php

Then

foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
    $t = explode(".",$filename);
    ${strtolower($t[1])}= new ucfirst($t[1])(); // automatically create the object        

}
April 18, 2012

Swap class on click

Question by Will B

I’ve been trying to figure out how I’m supposed to change a class of an element when you click it.

At the moment i have two classes (cOpen and cClosed). When you open the page the div is set to ‘cClosed’.

<div id="camera" class="cClosed" onClick="cameraToggle('weekLoaderWrapper', 'cameraContainer');">Kamera</div></a>

The things within onClick is not relevant to my question btw..

I’ve also put this script in the code

$('#camera').click(function() {
    $(this).toggleClass('cOpen');
    $(this).toggleClass('cClosed');
});

What I want it to do is to when you press the “camera”-div the class simply swaps to cClosed instead of cOpen, and vice verse when you click it again. This isn’t working atm.

My problem is how i’m supposed to “toggle” the div so it swaps the class of the “camera”-div.

Answer by Starx

Why are you using two classes? Use one class to identify the open and none to denote closed.

$('#camera').click(function() {
    $(this).toggleClass('cOpen');
});
April 7, 2012

Is it possible ? "Javascript Subclass"

Question by EyeSalut

I want to know i can do something “similar” to this (not working) code in javascript ?

function Player ()     {

    this.Inventory = function ()     {

        this.Inventory.UseItem = function(item_id)    {
            /* use the item ... */
        }

    }

}

and then use it like that :

current_player = new Player();
current_player.Inventory.UseItem(4);

Answer by Starx

Yeah

function Player ()     {

    var Inventory = {


        UseItem : function(item_id)    {
            /* use the item ... */
        }

    };

}
March 31, 2012

In Object Oriented Programming which object should maintain the many to many relationship? (if there is one)

Question by Matt

I’ll use an example to illustrate this:

class Company {

}

class Person {

}

Company and Person hold a many to many relationship. A Person can belong to multiple Companies and a Company can hold multiple People.

Would I then need to create a third class:

class CompanyPerson {

}

or should the company handle it:

class Company {
    function add_person() {

    }
}

or maybe the Person should?

class Person {
    function add_to_company() {

    }
}

Answer by Starx

This depends on the use case, but generally many to many object relationship can be deployed using a reference class

class CompanyPersonRelationship {
    public $company;
    public $person;
}

So now, both company and person can keeps track of their relationship lie

class Company {
   public $persons = array();   
}

class Person {
   public $companies = array();
}
March 30, 2012

How to create a "listening(waiting?)" method

Question by Andrius Naruševičius

Lets say I have:

class X
{
    function a()
    {
        echo "Hello, ";
    }
    function b()
    {
        echo "John!";
    }
}

and then

Y = new X();
Y->a();

but once the method a is called, I also want the method b called immediately after it (so it kind of listens(waits?) till the moment when a is called and finished), so the output is

Hello, John

Is it possible to do that, and how that should look?
And no, calling $this->b(); at the end of method a is NOT a solution to what I want to do 🙂 Thanks in advance 🙂

Answer by Starx

You are searching for observer pattern. Read some example from the internet, you should be able to do what you are attempting.

However, A very simple example of using observer pattern:

class X
{
    private $observer;
    public function __construct() {
        $this -> observer = new XObserver();
    }

    function a() {
        echo "Hello,";      
        $this -> observer -> aExecuted($this);
    }

    function b() {
        echo "John!";
    }
}

class XObserver {

    public function aExecuted($obj) {
        return $obj -> b(); 
    }
}
March 25, 2012

Working with extended classes in PHP

Question by epic_syntax

I have 2 classes looking like this:

class db {

    protected $db;

    function __construct() {
        $this->connect();
    }

    protected function connect() {
        $this->db = new MySQLi(db_host, db_user, db_pass, db_name) or die($this->db->error);
        $this->db->set_charset('utf8');
    }

}

and

class sample extends db {

    protected $js_base_dir;

    public function __construct($js_base_dir = js_dir) {
        $this->js_base_dir = $js_base_dir . "/";
    }
 ....

I want to use $this->db inside second class, but __construct in sample class overrides first classes construct function. How to get $this-> db inside second class? Am I doung something wrong? if yes what’s proper way?

Answer by Starx

You can call parent class method, using parrent::methodName(). Similarly, you can use this to invoke parent’s constructor method as well as

parent::__construct();

Usage:

public function __construct($js_base_dir = js_dir) {
    parent::_construct();
    $this->js_base_dir = $js_base_dir . "/";
}

Apart from the manual read this article for extended explanation.

March 16, 2011

Need suggestions for naming 2 classes in PHP

Question by Jared

I have one class user that is initiated in /update/user.php when update.php is started. This class handles user related queries on the database, such as edit, delete, create, etc.

I’m in the process of creating a new class also named user in /src/user.php that will perform user related queries on the database but only to retrieve them (and output) them. Such as to retrieve their user id, usergroup, e-mail, etc.

I find the need to name them both user but obviously there will be conflicts when update.php is retrieved. What suggestions can you give for naming these two different classes, even though they are seperate areas in my library but perform similar operations?

Using PHP 4.

Answer by Fraser

If they both query, but only one writes, then I would suggest something like.

UserWrite
UserRead

or

UserCreate
UserAccess

Answer by Starx

I would suggest you create one class to create, edit, delete, and retrieve records related to the users. Then manage user Roles to limit the access to the methods, rather than creating two separate class for one object class.

Explanation with comparison to real world.

Let’s say we have class Car. When user with Mechanical Role (or a mechanic) uses the car class then, he will able to access methods like repair(), openHood(), where as when users with driving role (or drivers) will access drive() methods.

In this scenarios also it is very inappropriate to create CarMechanic class and CarDriver class.

I think I made my point.

August 13, 2010

Confusing JavaScript statement: "var x = new this();"

Question by user419125

I thought I understood the concept of the JavaScript prototype object, as well as [[proto]] until I saw a few posts regarding class inheritance.

Firstly, “JavaScript OOP – the smart way” at http://amix.dk/blog/viewEntry/19038

See the implementation section:

var parent = new this('no_init');

And also “Simple JavaScript Inheritance” on John Resig’s great blog.

var prototype = new this();

What does new this(); actually mean?

This statement makes no sense to me because my understand has been that this points to an object and not a constructor function. I’ve also tried testing statements in Firebug to figure this one out and all I receive is syntax errors.

My head has gone off into a complete spin.

Could someone please explain this in detail?

Answer by strager

AJS.Class effectively* translates this:

var Person = new AJS.Class({
    init: function(name) {
        this.name = name;
        Person.count++;
    },
    getName: function() {
        return this.name;
    }
});
Person.count = 0;

into this:

var Person = function (name) {
    this.name = name;
    Person.count++;
};

Person.prototype = {
    getName: function() {
        return this.name;
    }
};

Person.extend = AJS.Class.prototype.extend;
Person.implement = AJS.Class.prototype.implement;

Person.count = 0;

Therefore, in this case, this in AJS.Class.prototype.extend refers to Person, because:

Person.extend(...);
// is the same as
Person.extend.call(Person, ...);
// is the same as
AJS.Class.prototype.extend.call(Person, ...);

* There are a lot of cases I don’t go over; this rewrite is for simplicity in understanding the problem.

Answer by Starx

see this link http://www.quirksmode.org/js/this.html It will tell you about the this keyword, but I am not sure what this() is, may be its some kind of user defined function…… that you are not aware of…

...

Please fill the form - I will response as fast as I can!