I have some options stored in mysql. The table contains 4 columns that look like this:
option_id | option_name | option_default | option_user_value
------------------------------------------------------------
1 | timezone | Europe/Athens |
2 | mode | 1 |
3 | email | [email protected] |
So far I get that info from the db using something like the following php code:
$table = 'options';
$values = '
option_name,
option_default,
option_user_value
';
$where = null;
$options = get_db_entries($table, $values, $where);
if ($options)
{
foreach ($options as $db_entry)
{
if ($db_entry['option_name'] == 'timezone')
{ $_timezone = $db_entry['option_default']; }
if ($db_entry['option_name'] == 'mode')
{ $_mode = $db_entry['option_default']; }
if ($db_entry['option_name'] == 'email')
{ $_email = $db_entry['option_default']; }
}
}
Is there a more efficient way in order to avoid those 'if' statements there in the loop ? I mean is there a way to directly insert that info from those columns to each variable without IFs ?
Just out of curiosity, please check my get_db_entries() function too if you want.
I am still learning (not familiar with OO yet) and thanks in advance.
Have a nice day.
function get_db_entries($table, $values, $where)
{
$db_host = '........';
$db_name = '........';
$db_user = '........';
$db_pass = '........';
// -----------------------------------------------------
$dbh = new PDO(
'mysql:host='.$db_host.'; dbname='.$db_name,
$db_user,
$db_pass,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
);
// -----------------------------------------------------
if ($where) { $where = ' WHERE '.$where; }
$sql = 'SELECT '.$values.' FROM '.$table.$where;
$results = $dbh->query($sql);
// -----------------------------------------------------
$results_array = array();
foreach ($results as $db_entry)
{ array_push($results_array, $db_entry); }
return $results_array;
}
if - thening your loop to death, why not just throw the results of the table into an array?