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
}