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

}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

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